Friday, September 25, 2015
Upload file đơn giản với JSF 2.2
[embed]https://youtu.be/caDsv_-EHPY[/embed]
1. Tạo Website sử dụng JSF 2.2
2. Tạo managebean như sau:
[sourcecode language="java"]
package codes;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.Part;
/**
*
* @author ntdan
*/
@ManagedBean
@RequestScoped
public class Upload_File {
private Part file;
private String fileName;
private long fileSize;
/**
* Creates a new instance of Upload_File
*/
public Upload_File() {
}
public Part getFile() {
return file;
}
public void setFile(Part file) {
this.file = file;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String upload()
{
try {
// get name of selected file
fileName = file.getSubmittedFileName();
// get file's size
fileSize = file.getSize();
// get fullpath of opload folder in web root
String dirPath= FacesContext.getCurrentInstance().getExternalContext().getRealPath("/upload");
// write file to upload folder
file.write(dirPath + "/" + fileName);
} catch (IOException ex) {
Logger.getLogger(Upload_File.class.getName()).log(Level.SEVERE, null, ex);
}
return "view";
}
public long getFileSize() {
return fileSize;
}
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
}
[/sourcecode]
3. Tạo trang index.xhtml để upload file như sau:
[sourcecode language="html"]
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
Demo for upload file
<f:view>
<h:form enctype="multipart/form-data">
File:<br/>
<h:inputFile value="#{upload_File.file}"/>
<br/>
<h:commandButton value="Upload" action="#{upload_File.upload()}"/>
<br/>
File:${upload_File.fileName} - #{upload_File.fileSize} bytes !
</h:form>
</f:view>
</h:body>
</html>
[/sourcecode]
4. Tạo trang xem ảnh vừa upload và thông tin về hình
[sourcecode language="html"]
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<f:view>
<br/>
File:${upload_File.fileName} - #{upload_File.fileSize} bytes !
<br/>
<h:graphicImage url="/upload/#{upload_File.fileName}" width="400px"/>
</f:view>
</h:body>
</html>
[/sourcecode]
OK, chạy trang index.xhtml --> chonj file upload hệ thống sẽ chuyển qua trang view.xhtml để xem ảnh vừa upload.
Friday, September 4, 2015
Sử dụng ValueChangeEvent tren Java Server Face

Chọn loại sản phẩm -> danh sách sản phẩm sẽ được lọc lại:

1. Tạo website sử dụng framework Face 2x (1x cũng được)
2. Định nghĩa 2 ManageBean (Products và Categories) và 2 JavaBean (Product và Category)
3. Thiết kế giao diện trang index.xhtml
Trong ví dụng này tôi sử dụng Netbean để demo
Tạo ManageBean (Products và Categories)
- File -> New File -> Other -> Java Server Face -> JSF ManageBean
Products
[sourcecode language="java"]
package codes;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.event.ValueChangeEvent;
/**
*
* @author ntdan
*/
@ManagedBean
@RequestScoped
public class Products {
/**
* Creates a new instance of Products
*/
public Products() {
}
private Collection list;
private int id;
private int cid;
public int getCid() {
return cid;
}
public void setCid(int cid) {
this.cid = cid;
}
private String name;
private String price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public Collection getList() {
return list;
}
public void select_cid_change(ValueChangeEvent event)
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection("jdbc:sqlserver://172.16.160.81\\sql2008;"
+ "database=northwind;","sa","sa");
PreparedStatement comm = conn.prepareStatement("Select categoryid, productid, productname, unitprice"
+ " from products where categoryID=?");
comm.setInt(1, Integer.parseInt(event.getNewValue().toString()));
ResultSet rs = comm.executeQuery();
list = new ArrayList<Product>();
Product pro;
while(rs.next())
{
pro = new Product();
pro.setId(rs.getInt("productid"));
pro.setcId(rs.getInt("categoryid"));
pro.setName(rs.getString("productname"));
pro.setPrice(rs.getString("unitprice"));
list.add(pro);
}
} catch (Exception e) {
list = null;
}
}
}
[/sourcecode]
Categories
[sourcecode language="java"]
package codes;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
/**
*
* @author ntdan
*/
@ManagedBean
@RequestScoped
public class Categories {
public Categories() {
}
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private Collection list;
public Collection getList() {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection("jdbc:sqlserver://172.16.160.81\\sql2008;"
+ "database=northwind;", "sa", "sa");
PreparedStatement comm = conn.prepareStatement("Select categoryid, categoryname"
+ " from categories");
ResultSet rs = comm.executeQuery();
list = new ArrayList<Category>();
Category ca;
while (rs.next()) {
ca = new Category();
ca.setId(rs.getInt("categoryid"));
ca.setName(rs.getString("categoryname"));
list.add(ca);
}
} catch (Exception e) {
list = null;
}
return list;
}
}
[/sourcecode]
Tạo 2 javabean như sau
- File -> New File -> Java Class
Product
[sourcecode language="java"]
package codes;
public class Product {
public Product() {
}
private int id;
private int cId;
private String name;
private String price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getcId() {
return cId;
}
public void setcId(int cId) {
this.cId = cId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
[/sourcecode]
Category
[sourcecode language="java"]
package codes;
public class Category {
public Category() {
}
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
[/sourcecode]
Thiết kế giao diện xhtml
[sourcecode language="html"]
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>Value Change Event</title>
<link type="text/css" rel="stylesheet" href="//codeproject.cachefly.net/App_Themes/CodeProject/Css/Main.min.css?dt=2.8.150901.1"></link>
</h:head>
<h:body>
<f:view>
<h:form>
Categories:<br/>
<h:selectOneMenu onchange="submit();"
value="#{products.cid}"
valueChangeListener="#{products.select_cid_change}">
<f:selectItems value="#{categories.list}" var="sate"
itemLabel="#{sate.name}"
itemValue="#{sate.id}"/>
</h:selectOneMenu>
<h:dataTable border="1" id="t" width="100%"
value="#{products.list}" var="product">
<h:column>
<f:facet name="header">
ID
</f:facet>
<h:outputText value="#{product.id}"/>
</h:column>
<h:column>
<f:facet name="header">
Name
</f:facet>
<h:outputText value="#{product.name}"/>
</h:column>
<h:column>
<f:facet name="header">
Price
</f:facet>
<h:outputText value="#{product.price}"/>
</h:column>
<h:column>
<f:facet name="header">
Operation
</f:facet>
<h:commandLink value="Delete" action="index"/>
</h:column>
</h:dataTable>
</h:form>
</f:view>
</h:body>
</html>
[/sourcecode]
f:selectItems: sẽ render các phần tử (thẻ option của HTML) cho hộp chọn (thẻ select của HTML) với nội dung giữa thẻ option là tên nhóm sản phẩm (itemLabel="#{sate.name}") và thuộc tính value của option sẽ được điền mã nhóm (itemValue="#{sate.id}").
Mỗi khi chọn một phần tử trong hộp chọn sự kiện onchange sẽ phát sinh (HTML), chúng ta có thể đón nhận sự kiện này dưới ManageBean qua thuộc tính valueChangeListener="#{products.select_cid_change}" của selectOneMenu để xử lý sự kiên và cập nhật lại danh sách sản phẩm.
Mã nguồn tham khảo --> ở đây
Thursday, September 11, 2014
JSF and Strut questions and anwsers
- Struts was first developed
- in an online exchange between several open source developers
- over a long holiday weekend(TRUE)
- as a commercial package
- The reset method on an ActionForm
- Sets all properties to their initial value
- Sets all properties to null
- Repopulates all properties from the request parameters
- None of the above(TRUE)
- Each Struts Action element is uniquely identified by its
- Input attribute
- Name attribute
- Page attribute
- Path attribute(TRUE)
- The name of the Application Resources file is set by the servlet init-param named
- Application(TRUE)
- Resources
- ApplicationResources
- messages
- The validating init-param of the ActionServlet is used to
- Bypass calls to the ActionForm validate method
- Bypass validation of the Struts configuration file(TRUE)
- Generate an error message if an unknown message key is used
- To specify an ActionMapping to use when a request doesn't match any other mapping, you can
- Use an asterisk for the path property
- Set the "default" property of the mapping to "true"
- Set the "unknown" property of the mapping to "true"(TRUE)
- Set the "missing" init-param of the ActionServlet to the mapping's path
- In Struts 1.1, you can change how Struts populates a form by
- Overriding the populate method of the ActionForm
- Overriding the processPopulate method of the Request Processor(TRUE)
- Overriding the populateBean method of the ActionMapping
- The < bean:write > tag is:
- Always converts HTML markup to entity equivalents, like <
- Never converts HTML markup to entity equivalents
- Converts markup when filter=true(TRUE)
- Converts markup when markup=false
- From a MVC perspective, Struts provides the
- Model
- View
- Controller(TRUE)
- Struts Framework is well suited for application of ____ size.
- Small
- Any(TRUE)
- Average
- Very small
- MVC is :
- Mode-View-Controller
- Model-View-Converter
- Model-Viewer-Controller
- Model-View-Controller(TRUE)
- What is Action Class ?
- The Action Class is a wrapper around the business logic and is a part of Model(TRUE)
- Nothing special about the Action class
- Action Class is a wrapper around the Internet logic
- None of the above
- An ActionForm is a JavaBean which extends the:
- struts.action.ActionForm(TRUE)
- apache.struts.action.ActionForm
- action.ActionForm
- ActionForm
- Use the following command (tag) to display the error on the jsp page:
- < html:errors/ >
- < html:errors/ >(TRUE)
- < errors / >
- < html=errors/ >
- What of following features can _not_ be configured in the JSF configuration file?
- Navigation rules
- Managed Beans
- Custom components
- Application Name(TRUE)
- In JSF - Which tag must enclose all other tags on a Faces JSP page?
- < f:faces >
- < f:view >(TRUE)
- < h:jsf >
- < h:view >
- In JSF - Why does the HtmlForm component render a <hidden> field?
- Command events
- Submit events
- Action events(TRUE)
- Click events
- In JSF - Why does the HtmlForm component render a < hidden > field
- To keep track of its identifier
- To keep track of the components in tree
- To set its submitted property(TRUE)
- For JavaScript integration
- What are the main features of JSF ? ( Choose many )
- Page navigation specification(TRUE)
- Standard user interface components like input fields, buttons, and links(TRUE)
- Read xml file
- Easy error handling(TRUE)
- In JSF - Components can be nested within another component
- True(TRUE)
- False
Next 20 -->
- Which one of the following tags renders a single radio button?
- <h:selectBooleanCheckbox>
- <h:selectOneRadio>
- <h:selectOneCheckbox>
- <h:selectManyCheckbox>
- The tag library that allows you to keep common content in a Web application, at a common location and insert it where necessary is
- HTML tag library
- Logic tag library
- Bean tag library
- Template tag library
- The tag used to create an input field that is not visible to the user is _______________.
- <h:inputSecret>
- <h:inputHidden>
- <h:inputPassword>
- <h:inputText>
- ______________ class is used to uniquely represent a locale of a country.
- faces.render.Locale
- util.Locale
- faces.context.Locale
- Creating and using a custom converter requires implementing _____________ and _____________ methods provided by Converter interface.
- getObject()
- getAsObject()
- getAsString()
- getString()
- It is possible to have more than one Faces configuration file.
- True
- False
- ________ classplays the role of the controller and is responsible for handling all the requests.
- Action
- ActionServlet
- RequestProcessor
- Plugin
- The tag used to create a text box to accept a password is _______________.
- <h:inputSecret>
- <h:inputHidden>
- <h:inputPassword>
- <h:inputText>
- Which of the following UI Component acts as a container for all other components?
- UIParameter
- UIForm
- UIViewRoot
- UISelectItem
- Which of the following statements are true about the reset() method of ActionForm class?
- Sets all properties to their initial value
- Sets all properties to null
- Repopulates all properties from the request parameters
- None of the above
- _______________________ declares a set of rules that define the next view for the user based on his/her actions.
- JSF Navigation Model
- JSF View Model
- JSF Forward Model
- JSF Model
- The file that provides a set of utility classes and interfaces that handle data structures used to store data in an application is _________.
- commons-beanutils.jar
- commons-collections.jar
- commons-digester.jar
- commons-logging.jar
- Which method of ActionServlet class maps the servlet name to a URL in the Web application?
- init()
- save()
- addmapping()
- addServletMapping()
- The JSF tag used to show all the error messages in a JSP page is ____________.
- <h:message>
- <h:messages>
- <f:messages>
- <f:message>
- Which one of the following JSF expressions, references an application's context path?
- #{contextPath}
- #{requestContextPath}
- #{facesContext.externalContext.requestContextPath}
- ${request.contextPath}
- Each Struts Action element is uniquely identified by its __________.
- Input attribute
- Name attribute
- Path attribute
- Page attribute
- Which one of the following events is generated by the <h:commandButton> tag of JSF ?
- Command event
- Submit event
- Action event
- Click event
- Which one of the following Action classes provides a mechanism for switching between modules in a modularized Struts application?
- SwitchAction
- DispatchAction
- IncludeAction
- LocaleAction
- The Struts class which handles the actual execution of the request is ________.
- ActionForward
- Action
- RequestProcessor
- ActionServlet
- The Struts tag used to display the error in the JSP page is ______________.
- <html:errors/>
- <html:errors>
- <errors>
- <html=errors>
Next 13 (sun)
- Struts was first developed
- in an online exchange between several open source developers
- over a long holiday weekend
- as a commercial package
- The reset method on an ActionForm
- Sets all properties to their initial value
- Sets all properties to null
- Repopulates all properties from the request parameters
- None of the above (do nothing)
- Each Struts Action element is uniquely identified by its
- Input attribute
- Name attribute
- Page attribute
- Path attribute
- The name of the Application Resources file is set by the servlet init-param named
- application
- resources
- ApplicationResources
- messages
- The validating init-param of the ActionServlet is used to
- Bypass calls to the ActionForm validate method
- Bypass validation of the Struts configuration file
- Generate an error message if an unknown message key is used
- To specify an ActionMapping to use when a request doesn't match any other mapping, you can
- Use an asterisk for the path property
- Set the "default" property of the mapping to "true"
- Set the "unknown" property of the mapping to "true"
- Set the "missing" init-param of the ActionServlet to the mapping's path
- If you have created a custom ActionMapping subclass with the property "service", you can initialize the value to "selectRecord" using
- <init-property name="service" value="selectRecord"/>
- <set-property property="service" value="selectRecord"/>
- <put-field key="service" content="selectRecord"/>
- In Struts 1.1, you can change how Struts populates a form by
- Overriding the populate method of the ActionForm
- Overriding the processPopulate method of the Request Processor
- Overriding the populateBean method of the ActionMapping
- The <bean:write> tag is:
- Always converts HTML markup to entity equivalents, like <
- Never converts HTML markup to entity equivalents
- Converts markup when filter=true
- Converts markup when markup=false
- To prevent possible security issues with the <html:password> tag, you should
- Call the reset method if validation fails
- Set the tag's redisplay property to false
- Set the tag's reset property to false
- Use a plain html tag instead
- To localize Tiles, you can
- Create separate configuration files for each locale
- Specify an locale for a definition
- Either A or B
- To localize Validator forms, you can
- Create separate configuration files for each locale
- Specify a locale for a form-set
- Either A or B
- From a MVC perspective, Struts provides the
- Model
- View
- Controller
Next 20 -->> 20 question_3
Thursday, September 4, 2014
Strut2 ví dụ căn bản
Basic exercise:
Using Strut 2 to develop login application.
If login fail
If login successful
1. Create Java web application base on Strut2 framework as figure below.
2. Create some file as structure
3. Open struts.xml and modify as
4. Open appResources: create some keys
5. Open Login class and add new code as
6. Generate getter/setter for two field above
7. Next, design login page
8. Next, index.jsp page
9. Next, error.jsp page
10. Now, deploy and run login.jsp page
Strut2-Validation
Using Strut validate input data
If input data invalid
If input data is valid
1. Design customer.jsp as
2. Add some new key to appResources
3. Assign Customer action in struts.xml
4. Add new class with name “Customer” into codes package
5. Generate setter and getter for 4 fields
6. Add new file “Customer-validation.xml” into package
Now, re-deploy and run
Using annotations
All action class must be inside actions package
Strut Controller now change to org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
1 <filter>
2 <filter-name>struts2</filter-name>
3 <filter-class>
4 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
5 </filter-class>
6 <init-param>
7 <param-name>actionPackages</param-name>
8 <param-value>codes</param-value>
9 </init-param>
10 </filter>
11 <filter-mapping>
12 <filter-name>struts2</filter-name>
13 <url-pattern>/*</url-pattern>
14 </filter-mapping>
If your Action extend from ActionSupport, then your Action class name has no rule required.
Ex: Login action beloved
Otherwise, action class name must end with Action string
Ex: account action
1 @Namespace("/")
2 @ResultPath(value = "/")
3 @Results({
4 @Result(name = "success", location = "index.jsp"),
5 @Result(name = "error", location = "error.jsp")}
6 )
7 public class accountAction {
8 @Action(value="account")
9 public String execute() throws Exception {
10 if ("nvmit".equals(getName())) {
11 return SUCCESS;
12 } else {
13 return ERROR;
14 }
15 }
16 private String name ="";
17 public String getName() {
18 return name;
19 }
20 public void setName(String name) {
21 this.name = name;
22 }
23 }
@Namespace Annotation in Struts 2
@Namespace is used at class level or package level. This helps to change the namespace for action class. While accessing or calling action class, it hides package structure. When namespace is applied at package level, all the action of that package gets that namespace as default.
1 @Results({
2 @Result(name = "SUCCESS", location = "/user/index.jsp"),
3 @Result(name = "ERROR", location = "/user/error.jsp")
4 })
5 @Namespaces(
6 @Namespace("/user")
7 )
8 public class Login extends ActionSupport{
9 @Action(value = "/user/login")
10 public String execute() throws Exception {
11 if ("nvmit".equals(getName()) && "nvmit".equals(getPwd())) {
12 return "SUCCESS";
13 } else {
14 return "ERROR";
15 }
16 }
17
18 //Java Bean to hold the form parameters
19 private String name;
20 private String pwd;
21
22 public String getName() {
23 return name;
24 }
25
26 public void setName(String name) {
27 this.name = name;
28 }
29
30 public String getPwd() {
31 return pwd;
32 }
33
34 public void setPwd(String pwd) {
35 this.pwd = pwd;
36 }
37 }
38
The above class can be accessed by @Namespace + @Action that is /user/form
http://localhost:8080/Struts2Demo-1/user/form
Create Project with beloved structure
Project Structure
user/login.jsp
1 <%@ taglib uri="/struts-tags" prefix="s"%>
2 <html>
3 <head>
4 <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
5 <title>Login Page</title>
6 </head>
7 <body>
8 <h3>Welcome User, please login below</h3>
9 <s:form action="/user/login">
10 <s:textfield name="name" label="User Name"></s:textfield>
11 <s:textfield name="pwd" label="Password" type="password"></s:textfield>
12 <s:submit value="Login"></s:submit>
13 </s:form>
14 </body>
15 </html>
user/index.jsp
1 <%@page contentType="text/html" pageEncoding="UTF-8"%>
2 <%@taglib prefix="s" uri="/struts-tags" %>
3 <!DOCTYPE html>
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
7 <title>JSP Page</title>
8 </head>
9 <body>
10 <h1>Hello <s:property value="name" /></h1>
11 </body>
12 </html>
account.jsp
1 <%@page contentType="text/html" pageEncoding="UTF-8"%>
2 <%@taglib prefix="s" uri="/struts-tags" %>
3 <!DOCTYPE html>
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
7 <title>JSP Page</title>
8 </head>
9 <body>
10 <h1>Hello <s:property value="name" /></h1>
11 </body>
12 </html>
13
Index.jsp same above
Download source code ===> here
Thursday, October 31, 2013
Java server face (JSF) - trang đa ngôn ngữ
- -Create jsf web page support multi language interface
- -Using Face component Event
- -Setting current Locale and Global Locale
Hints:
- Create JSF web site
- Create 03 jsp page and configure navigation rule for them from properties file support two language Vietnam and English
- Setting current Locale and Global Locale at runtime and design time
Create JSF website
- Create 03 jsp file: index.jsp, add.jsp, list.jsp
- Open Face-config.xml, design navigation rule as figure 01 and insert new code as code 01
[sourcecode language="xml"]
<application>
<view-handler>com.sun.facelets.FaceletViewHandler</view-handler>
<resource-bundle>
<var>bundle</var>
<base-name>code.guiMessage</base-name>
</resource-bundle>
<locale-config>
<default-locale>vi</default-locale>
</locale-config>
</application>
[/sourcecode]
Code 01: Register bundle file
Create properties file
- Name: guiMessage in side package code
- Add two Locale vi_VN and en_US
- Rename file as figure 02
Right click o guiMessage file select open and insert some key as figure 03
Create manage bean
- Language in code package
- Modified code as
[sourcecode language="java"]
package code;
import java.util.Locale;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
public class language {
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
String lang = &amp;quot;vi&amp;quot;;
/**
* Creates a new instance of language
*/
public language() {
}
public void change(ValueChangeEvent event) {
lang = event.getNewValue().toString();
FacesContext.getCurrentInstance().getApplication().setDefaultLocale(new Locale(lang));
FacesContext.getCurrentInstance().getViewRoot().setLocale(new Locale(lang));
}
}
[/sourcecode]
This code allow we setting Local and Global Locale of websie
Open index.jsp
Modified as figure 03 (using EL language: after bundle. Using Ctrl+Space bar for virtual code)
Index.jsp with two language
Add Add.jsp page
[sourcecode language="html"]
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<f:view>
<h:form>
<table>
<tr>
<td align="center" colspan="2">
<h1><h:outputText value="#{bundle.register}"/></h1>
<h4><h:commandLink value="#{bundle.home}" action="home"/></h4>
<h:messages layout="table"/>
</td>
</tr>
<tr>
<td>
<h:outputText>
<f:attribute name="value" value="#{bundle.id}"/>
</h:outputText>
</td>
<td>
<h:inputText value="#{Customer.customerID}">
</h:inputText>
</td>
</tr>
<tr>
<td><h:outputText value="#{bundle.CompanyName}"/></td>
<td><h:inputText value="#{Customer.companyName}"/></td>
</tr>
<tr>
<td><h:outputText value="#{bundle.Address}"/></td>
<td><h:inputText value="#{Customer.address}"/></td>
</tr>
<tr>
<td></td> <td><h:commandButton value="#{bundle.register}" action="list"
actionListener="#{Customer.AddNew}"/></td>
</tr>
</table>
</h:form>
</f:view>
[/sourcecode]
Friday, October 25, 2013
Tài nguyên tham khảo JSF tiếng Việt
http://www.ibm.com/developerworks/vn/edu/j-jsf1/index.html
http://www.ibm.com/developerworks/vn/edu/j-jsf2/index.html
Wednesday, January 30, 2013
Simple demo product buying FaceFramework
Simple demo product buying FaceFramework netbean 7.1
Ma nguon