You are on page 1of 97

In JSF 2.

0, all your web resources files like css, images or JavaScript, should put in resources
folder, under the root of your web application (same folder level with WEB-INF ).
The sub-folder under resources folder is consider as library or project theme, later you can
reference those resources with library attribute. This new JSF resources management
mechanism is really useful, it allow developer to change the web resources easily by theme/library
or versioning.
See below examples :
Figure 1-0 : Example of a JSF2 project folder structure.

1. Normal Example
Here are some examples using resources and library in JSF 2.0.
1.

Include CSS file h:outputStylesheet

<h:outputStylesheet library="theme1" name="css/style.css" />

HTML output
<link type="text/css" rel="stylesheet"
href="/JavaServerFaces/faces/javax.faces.resource/css/style.css?
ln=theme1" />

2.

Display images h:graphicImage

<h:graphicImage library="theme1" name="img/sofa.png" />

HTML output
<img src="/JavaServerFaces/faces/javax.faces.resource/img/sofa.png?
ln=theme1" />

3.

Include JavaScript h:outputScript

<h:outputScript library="theme1" name="js/hello.js" />

HTML output
<script type="text/javascript"
src="/JavaServerFaces/faces/javax.faces.resource/js/hello.js?
ln=theme1">

2. Versioning Example

Refer to Figure 1-0, create a version folder matching regex \d+(_\d+)* under library folder, and
the default JSF ResourceHandler will always get the highest version to display.
P.S Assume your project is Figure 1-0 structure
Include CSS file h:outputStylesheet

<h:outputStylesheet library="default" name="css/style.css" />

Since default theme contains version 1_0 and 2_0, JSF will always get the resources from the
highest version, and append the version at the end of the resource.
See HTML output :
<link type="text/css" rel="stylesheet"
href="/JavaServerFaces/faces/javax.faces.resource/css/style.css?
ln=default&amp;v=2_0" />

Redirection
By default, JSF 2 is perform a forward while navigating to another page, it caused the page URL is
always one behind :). For example, when you move from page1.xhtml to page2.xhtml, the
browser URL address bar will still showing the same page1.xhtml URL.
To avoid this, you can tell JSF to use the redirection by append the faces-redirect=true to the end
of the outcome string.
<h:form>
<h:commandButton action="page2?faces-redirect=true" value="Move to
page2.xhtml" />
</h:form>

Note
For simple page navigation, this new implicit navigation is more then enough; For complex page
navigation, you are still allow to declare the page flow (navigation rule) in the faces-config.xml file.

Page forward.
<h:form>
<h:commandButton action="page1" value="Page1" />
</h:form>

Page redirection.
<h:form>
<h:commandButton action="page1?faces-redirect=true" value="Page1" />
</h:form>

In the navigation rule, you can enable the page redirection by adding a <redirect /> element within
the <navigation-case /> .

<navigation-rule>
<from-view-id>start.xhtml</from-view-id>
<navigation-case>
<from-outcome>page1</from-outcome>
<to-view-id>page1.xhtml</to-view-id>
<redirect />
</navigation-case>
</navigation-rule>

In this tutorial, we demonstrate the use of resource bundle to display messages in JSF 2.0. For
maintainability concern, its always recommended to put all the messages in properties file, instead
of hard-code the message in page directly.

1. Properties File

Create a properties file, contains message for the page, and put it into the projects resource folder,
see figure below
messages.properties
message = This is "message"
message.test1 = This is "message.test1"
message.test2 = This is "<h2>message.test3</h2>"
message.test3 = This is "&lt;h2&gt;message.test4&lt;/h2&gt;"
message.param1 = This is "message.param1" - {0}
message.param2 = This is "message.param2" - {0} and {1}

Project folder structure.

2. Using Resource Bundles


There are two ways to load the properties file into JSF 2.0.

1. Global Resource Bundle


To load the properties file globally, so that all the jsf pages can access the messages. You can create
a faces-config.xml file and declare the properties file explicitly.
faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
<application>
<resource-bundle>
<base-name>com.mkyong.messages</base-name>
<var>msg</var>
</resource-bundle>
</application>
</faces-config>

2. Local Resource Bundle


To load the properties file locally, or for specified page only. Declare the <f:loadBundle /> tag in the
page that need to access the message in the messages.properties.
<f:loadBundle basename="com.mkyong.messages" var="msg"/>

3. JSF 2.0 Pages

In this case, the messages.properties file is given a name of msg, to access the message, just
use msg.key.
hello.xhtml
<?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:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">

<h:body>
<h2>JSF 2.0 and Resource Bundles Examples</h2>
<ol>

<li><h:outputText value="#{msg.message}" /></li>

<li><h:outputText value="#{msg['message.test1']}" /></li>

<li><h:outputText value="#{msg['message.test2']}" /></li>

/></li>

<li><h:outputText value="#{msg['message.test2']}" escape="false"

<li><h:outputText value="#{msg['message.test3']}" /></li>

/></li>

<li><h:outputText value="#{msg['message.test3']}" escape="false"

<li>
<h:outputFormat value="#{msg['message.param1']}">
<f:param value="param0" />
</h:outputFormat>
</li>
<li>
<h:outputFormat value="#{msg['message.param2']}">
<f:param value="param0" />
<f:param value="param1" />
</h:outputFormat>
</li>
</ol>
</h:body>
</html>

4. How it works?
Example 1
A normal way to access the message.
<h:outputText value="#{msg.message}" />

//properties file
message = This is "message"

Example 2
For a key that has a dot . as name, you cant use the normal way #{msg.message.test1}, it will
not work. Instead, you should use bracket like #{msg['message.test1']}.
<h:outputText value="#{msg['message.test1']}" />

//properties file
message.test1 = This is "message.test1"

Example 3
To display HTML tag in the message, just add the escape attribute and set it to false.
<h:outputText value="#{msg['message.test2']}" />
<h:outputText value="#{msg['message.test2']}" escape="false" />
<h:outputText value="#{msg['message.test3']}" />
<h:outputText value="#{msg['message.test3']}" escape="false" />

//properties file
message.test2 = This is "<h2>message.test3</h2>"
message.test3 = This is "&lt;h2&gt;message.test4&lt;/h2&gt;"

Example 4
For a parameter message, just use the <h:outputFormat /> and <f:param / > tag.
<h:outputFormat value="#{msg['message.param1']}">
<f:param value="param0" />
</h:outputFormat>
<h:outputFormat value="#{msg['message.param2']}">
<f:param value="param0" />

<f:param value="param1" />


</h:outputFormat>

//properties file
message.param1 = This is "message.param1" - {0}
message.param2 = This is "message.param2" - {0} and {1}

5. Demo
URL : http://localhost:8080/JavaServerFaces/hello.jsf

In JSF application, you can change your application locale programmatically like this :
//this example change locale to france

FacesContext.getCurrentInstance().getViewRoot().setLocale(new Locale('fr');

It makes JSF support for internationalization or multiple languages easily.

Complete JSF internationalization example


In this tutorial, we show you a JSF 2.0 web application, which display a welcome page, retrieve a
welcome message from properties file, and change the welcome message dynamically based on the
selected language.

1. Project Folder
Directory structure for this example.

2. Properties file
Heres two properties files to store English and Chinese message.
welcome.properties
welcome.jsf = Happy learning JSF 2.0

welcome_zh_CN.properties
welcome.jsf = \u5feb\u4e50\u5b66\u4e60 JSF 2.0

Note
For UTF-8 or non-English characters, for example Chinese , you should encode it
with native2ascii tool.

3. faces-config.xml
Include above properties file into your JSF application, and declared en as your default application
locale.
faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
<application>
<locale-config>

<default-locale>en</default-locale>
</locale-config>
<resource-bundle>
<base-name>com.mkyong.welcome</base-name>
<var>msg</var>
</resource-bundle>
</application>
</faces-config>

4. Managed Bean
A managed bean, which provide language selection list , and a value change event listener to
change the locale programmatically.
LanguageBean .java
package com.mkyong;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import javax.faces.event.ValueChangeEvent;

@ManagedBean(name="language")
@SessionScoped
public class LanguageBean implements Serializable{

private static final long serialVersionUID = 1L;

private String localeCode;

private static Map<String,Object> countries;


static{
countries = new LinkedHashMap<String,Object>();
countries.put("English", Locale.ENGLISH); //label, value
countries.put("Chinese", Locale.SIMPLIFIED_CHINESE);
}

public Map<String, Object> getCountriesInMap() {


return countries;
}

public String getLocaleCode() {


return localeCode;

public void setLocaleCode(String localeCode) {


this.localeCode = localeCode;
}

//value change event listener


public void countryLocaleCodeChanged(ValueChangeEvent e){

String newLocaleValue = e.getNewValue().toString();

//loop country map to compare the locale code


for (Map.Entry<String, Object> entry : countries.entrySet()) {

if(entry.getValue().toString().equals(newLocaleValue)){

FacesContext.getCurrentInstance()

.getViewRoot().setLocale((Locale)entry.getValue());

}
}
}

5. JSF Page
A JSF page to display a welcome message from properties file, and attach a value change event
listener to a dropdown box.
<?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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
>

<h:body>

<h1>JSF 2 internationalization example</h1>

<h:form>

<h3>
<h:outputText value="#{msg['welcome.jsf']}" />
</h3>

<h:panelGrid columns="2">

Language :
<h:selectOneMenu value="#{language.localeCode}"
onchange="submit()"

valueChangeListener="#{language.countryLocaleCodeChanged}">
<f:selectItems value="#{language.countriesInMap}" />
</h:selectOneMenu>

</h:panelGrid>

</h:form>

</h:body>
</html>

6. Demo
URL : http://localhost:8080/JavaServerFaces/faces/default.xhtml
Default, locale English is display.

If user changes the dropdown box language, it will fire a value change event listener and change the
application locale accordingly.

In JSF, <h:selectBooleanCheckbox /> tag is used to render a single HTML input element of
checkbox type.
//JSF...
<h:selectBooleanCheckbox value="#{user.rememberMe}" /> Remember Me

//HTML output...
<input type="checkbox" name="j_idt6:j_idt8" /> Remember Me

While <h:selectManyCheckbox /> tag is used to render a set of HTML input element of type
checkbox, and format it with HTML table and label tags.
//JSF...
<h:selectManyCheckbox value="#{user.favNumber1}">
<f:selectItem itemValue="1" itemLabel="Number1 - 1" />
<f:selectItem itemValue="2" itemLabel="Number1 - 2" />
<f:selectItem itemValue="3" itemLabel="Number1 - 3" />
</h:selectManyCheckbox>

//HTML output...
<table>
<tr>
<td>
<input name="j_idt6:j_idt10" id="j_idt6:j_idt10:0" value="1"
type="checkbox" />
<label for="j_idt6:j_idt10:0" class=""> Number1 - 1</label></td>
<td>
<input name="j_idt6:j_idt10" id="j_idt6:j_idt10:1" value="2"
type="checkbox" />
<label for="j_idt6:j_idt10:1" class=""> Number1 - 2</label></td>
<td>

<input name="j_idt6:j_idt10" id="j_idt6:j_idt10:2" value="3"


type="checkbox" />
<label for="j_idt6:j_idt10:2" class=""> Number1 - 3</label></td>
<td>
</tr>
</table>

JSF 2.0 example


Heres a JSF 2.0 example to show the use of h:selectBooleanCheckbox and
h:selectManyCheckbox tags.
h:selectBooleanCheckbox
Render a single checkbox, and wire it with a boolean property.
h:selectManyCheckbox
Render a group of checkboxes and populate the data in different ways :
1.

Hardcoded value in f:selectItem tag.

2.

Generate values with an Array and put it into f:selectItems tag.

3.

Generate values with a Map and put it into f:selectItems tag.

4.

Generate values with an Object array and put it into f:selectItems tag, then represent the
value with var attribute.

1. Backing Bean
A backing bean to hold the submitted checkboxes values.
package com.mkyong;

import java.util.Arrays;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name="user")
@SessionScoped
public class UserBean{

public boolean rememberMe;


public String[] favNumber1;
public String[] favNumber2;
public String[] favNumber3;
public String[] favNumber4;

//getter and setter methods...

public String getFavNumber1InString() {


return Arrays.toString(favNumber1);
}

//Generated by Array
public String[] getFavNumber2Value() {

favNumber2 = new String[5];


favNumber2[0] = "Number2 - 1";
favNumber2[1] = "Number2 - 2";
favNumber2[2] = "Number2 - 3";
favNumber2[3] = "Number2 - 4";
favNumber2[4] = "Number2 - 5";

return favNumber2;
}

public String getFavNumber2InString() {


return Arrays.toString(favNumber2);
}

//Generated by Map
private static Map<String,Object> number3Value;
static{
number3Value = new LinkedHashMap<String,Object>();
number3Value.put("Number3 - 1", "1"); //label, value
number3Value.put("Number3 - 2", "2");
number3Value.put("Number3 - 3", "3");
number3Value.put("Number3 - 4", "4");

number3Value.put("Number3 - 5", "5");


}

public Map<String,Object> getFavNumber3Value() {


return number3Value;
}

public String getFavNumber3InString() {


return Arrays.toString(favNumber3);
}

//Generated by Object array


public static class Number{
public String numberLabel;
public String numberValue;

public Number(String numberLabel, String numberValue){


this.numberLabel = numberLabel;
this.numberValue = numberValue;
}

public String getNumberLabel(){


return numberLabel;
}

public String getNumberValue(){


return numberValue;
}

public Number[] number4List;

public Number[] getFavNumber4Value() {

number4List = new Number[5];


number4List[0] = new Number("Number4 - 1", "1");
number4List[1] = new Number("Number4 - 2", "2");
number4List[2] = new Number("Number4 - 3", "3");
number4List[3] = new Number("Number4 - 4", "4");
number4List[4] = new Number("Number4 - 5", "5");

return number4List;
}

public String getFavNumber4InString() {


return Arrays.toString(favNumber4);
}

A JSF page to demonstrate the use h:selectBooleanCheckbox and h:selectManyCheckbox


tags.
<?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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
>
<h:body>

<h1>JSF 2 checkboxes example</h1>


<h:form>

<h2>1. Single checkbox</h2>


<h:selectBooleanCheckbox value="#{user.rememberMe}" /> Remember Me

<h2>2. Mutiple checkboxes</h2>

1. Hard-coded with "f:selectItem" :


<h:selectManyCheckbox value="#{user.favNumber1}">
<f:selectItem itemValue="1" itemLabel="Number1 - 1" />

<f:selectItem itemValue="2" itemLabel="Number1 - 2" />


<f:selectItem itemValue="3" itemLabel="Number1 - 3" />
<f:selectItem itemValue="4" itemLabel="Number1 - 4" />
<f:selectItem itemValue="5" itemLabel="Number1 - 5" />
</h:selectManyCheckbox>

<br />

2. Generated by Array :
<h:selectManyCheckbox value="#{user.favNumber2}">
<f:selectItems value="#{user.favNumber2Value}" />
</h:selectManyCheckbox>

<br />

3. Generated by Map :
<h:selectManyCheckbox value="#{user.favNumber3}">
<f:selectItems value="#{user.favNumber3Value}" />
</h:selectManyCheckbox>

<br />

4. Generated by Object with var :


<h:selectManyCheckbox value="#{user.favNumber4}">

<f:selectItems value="#{user.favNumber4Value}" var="n"


itemLabel="#{n.numberLabel}"
itemValue="#{n.numberValue}" />
</h:selectManyCheckbox>

<br />

<h:commandButton value="Submit" action="result" />


<h:commandButton value="Reset" type="reset" />

</h:form>

</h:body>
</html>

result.xhtml
<?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://java.sun.com/jsf/html"
>

<h:body>

<h1>JSF 2 checkboxes example</h1>

<h2>result.xhtml</h2>

<ol>
<li>user.rememberMe : #{user.rememberMe}</li>
<li>user.favNumber1 : #{user.favNumber1InString}</li>
<li>user.favNumber2 : #{user.favNumber2InString}</li>
<li>user.favNumber3 : #{user.favNumber3InString}</li>
<li>user.favNumber4 : #{user.favNumber4InString}</li>
</ol>
</h:body>

</html>

3. Demo

When submit button is clicked, link to result.xhtml page and display the submitted checkboxe
values.

How to checked checkboxs value by default?


h:selectBooleanCheckbox
The value of f:selectItem tag is checked if the boolean value is set to true. In above example, if you
set boolean property rememberMe to true :
@ManagedBean(name="user")
@SessionScoped
public class UserBean{

public boolean rememberMe = true;

//...

The rememberMe checkbox value is checked by default.

h:selectManyCheckbox
The values of f:selectItems tag are checked if it matched to the value of h:selectManyCheckbox
tag. In above example, if you set favNumber3 to {1,3} :
@ManagedBean(name="user")
@SessionScoped
public class UserBean{

public String[] favNumber3 = {"1","3"};

//...

The favNumber3 checkboxes, Number 1 and Number 3 values are checked by default.

JSF 2.0 h:selectOneRadio example


A JSF 2.0 example to show the use of h:selectOneRadio tag to render radio buttons, and
populate the data in 3 different ways :
1.

Hardcoded values in f:selectItem tag.

2.

Generate values with a Map and put it into f:selectItems tag.

3.

Generate values with an Object array and put it into f:selectItems tag, then represent the
value with a var attribute.

1. Backing Bean
A backing bean to hold the submitted data.
package com.mkyong;

import java.util.LinkedHashMap;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name="user")
@SessionScoped
public class UserBean{

public String favColor1;


public String favColor2;
public String favColor3;

//getter and setter methods

//Generated by Map
private static Map<String,Object> color2Value;
static{
color2Value = new LinkedHashMap<String,Object>();
color2Value.put("Color2 - Red", "Red"); //label, value
color2Value.put("Color2 - Green", "Green");
color2Value.put("Color3 - Blue", "Blue");
}

public Map<String,Object> getFavColor2Value() {


return color2Value;
}

//Generated by Object array


public static class Color{
public String colorLabel;
public String colorValue;

public Color(String colorLabel, String colorValue){


this.colorLabel = colorLabel;
this.colorValue = colorValue;
}

public String getColorLabel(){


return colorLabel;
}

public String getColorValue(){


return colorValue;
}

public Color[] color3List;

public Color[] getFavColor3Value() {

color3List = new Color[3];


color3List[0] = new Color("Color3 - Red", "Red");
color3List[1] = new Color("Color3 - Green", "Green");
color3List[2] = new Color("Color3 - Blue", "Blue");

return color3List;
}

2. JSF Page
A JSF page to demonstrate the use h:selectOneRadio tag.
<?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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
>

<h:body>

<h1>JSF 2 radio button example</h1>


<h:form>

1. Hard-coded with "f:selectItem" :


<h:selectOneRadio value="#{user.favColor1}">
<f:selectItem itemValue="Red" itemLabel="Color1 - Red"

/>

<f:selectItem itemValue="Green" itemLabel="Color1 -

Green" />

<f:selectItem itemValue="Blue" itemLabel="Color1 -

Blue" />

</h:selectOneRadio>

<br />

2. Generated by Map :
<h:selectOneRadio value="#{user.favColor2}">
<f:selectItems value="#{user.favColor2Value}" />
</h:selectOneRadio>

<br />

3. Generated by Object array and iterate with var :


<h:selectOneRadio value="#{user.favColor3}">

<f:selectItems value="#{user.favColor3Value}" var="c"


itemLabel="#{c.colorLabel}" itemValue="#{c.colorValue}"

/>

</h:selectOneRadio>

<br />

<h:commandButton value="Submit" action="result" />


<h:commandButton value="Reset" type="reset" />

</h:form>
</h:body>
</html>

result.xhtml
<?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://java.sun.com/jsf/html"
>
<h:body>

<h1>JSF 2 radio button example</h1>

<h2>result.xhtml</h2>

<ol>
<li>user.favColor1 : #{user.favColor1}</li>
<li>user.favColor2 : #{user.favColor2}</li>
<li>user.favColor3 : #{user.favColor3}</li>
</ol>
</h:body>
</html>

3. Demo

When submit button is clicked, link to result.xhtml and display the submitted radio button values.

How to select radio button value by default?


In JSF, the radio button values of f:selectItems tag is selected if it matched to the value of
h:selectOneRadio tag. In above example, if you set favColor2 to Red :
@ManagedBean(name="user")
@SessionScoped
public class UserBean{

public String[] favColor = "Red";

//...

The favColor2 radio button, Red option is selected by default.

h:selectOneListbox example
A JSF 2.0 example to show the use of h:selectOneListbox tag to render a single select listbox,
and populate the data in 3 different ways :
1.

Hardcoded value in f:selectItem tag.

2.

Generate values with a Map and put it into f:selectItems tag.

3.

Generate values with an Object array and put it into f:selectItems tag, then represent the
value with var attribute.

1. Backing Bean
A backing bean to hold and generate data for listbox values.
package com.mkyong;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name="user")
@SessionScoped
public class UserBean implements Serializable{

public String favYear1;


public String favYear2;

public String favYear3;

//getter and setter methods

//Generated by Map
private static Map<String,Object> year2Value;
static{
year2Value = new LinkedHashMap<String,Object>();
year2Value.put("Year2 - 2000", "2000"); //label, value
year2Value.put("Year2 - 2010", "2010");
year2Value.put("Year2 - 2020", "2020");
}

public Map<String,Object> getFavYear2Value() {


return year2Value;
}

//Generated by Object array


public static class Year{
public String yearLabel;
public String yearValue;

public Year(String yearLabel, String yearValue){


this.yearLabel = yearLabel;

this.yearValue = yearValue;
}

public String getYearLabel(){


return yearLabel;
}

public String getYearValue(){


return yearValue;
}

public Year[] year3List;

public Year[] getFavYear3Value() {

year3List = new Year[3];


year3List[0] = new Year("Year3 - 2000", "2000");
year3List[1] = new Year("Year3 - 2010", "2010");
year3List[2] = new Year("Year3 - 2020", "2020");

return year3List;
}

2. JSF Page
A JSF page to demonstrate the use h:selectOneListbox tag.
<?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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
>
<h:body>

<h1>JSF 2 listbox example</h1>


<h:form>

1. Hard-coded with "f:selectItem" :


<h:selectOneListbox value="#{user.favYear1}">

/>

/>

/>

<f:selectItem itemValue="2000" itemLabel="Year1 - 2000"

<f:selectItem itemValue="2010" itemLabel="Year1 - 2010"

<f:selectItem itemValue="2020" itemLabel="Year1 - 2020"

</h:selectOneListbox>

<br />

2. Generated by Map :
<h:selectOneListbox value="#{user.favYear2}">
<f:selectItems value="#{user.favYear2Value}" />
</h:selectOneListbox>

<br />

3. Generated by Object array and iterate with var :


<h:selectOneListbox value="#{user.favYear3}">
<f:selectItems value="#{user.favYear3Value}" var="y"
itemLabel="#{y.yearLabel}" itemValue="#{y.yearValue}"
/>
</h:selectOneListbox>

<br />

<h:commandButton value="Submit" action="result" />


<h:commandButton value="Reset" type="reset" />

</h:form>
</h:body>

</html>

result.xhtml
<?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://java.sun.com/jsf/html"
>

<h:body>

<h1>JSF 2 listbox example</h1>

<h2>result.xhtml</h2>

<ol>
<li>user.favYear1 : #{user.favYear1}</li>
<li>user.favYear2 : #{user.favYear2}</li>
<li>user.favYear3 : #{user.favYear3}</li>
</ol>
</h:body>

</html>

3. Demo

When submit button is clicked, link to result.xhtml page and display the submitted listbox values.

How to pre-select a listbox value?


The value of f:selectItems tag is selected if it matched to the value of h:selectOneListbox tag.
In above example, if you set favYear1 property to 2010 :
@ManagedBean(name="user")
@SessionScoped
public class UserBean{

public String favYear1 = "2010";

//...

The favYear1 listbox, value 2010 is selected by default.


In JSF web application, h:outputFormat tag is similar with h:outputText tag, but with extra
function to render parameterized message. For example,
<h:outputFormat value="param0 : {0}, param1 : {1}" >
<f:param value="Number 1" />
<f:param value="Number 2" />
</h:outputFormat>

It will output the following result


param0 : Number 1, param1 : Number 2

1.

{0} match to <f:param value=Number 1 />

2.

{1} match to <f:param value=Number 2 />

OutputFormat example
See few use cases of h:outputFormat tag coded in JSF 2.0 web application.

1. Managed Bean
A managed bean, provide some text for demonstration.
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name="user")
@SessionScoped

public class UserBean{

public String text = "Hello {0}";


public String htmlInput = "<input type=\"{0}\" {1} />";

//getter and setter methods...


}

2. View Page
Page with few h:outputFormat tags example.
JSF
<?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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
>
<h:body>
<h1>JSF 2.0 h:outputFormat Example</h1>
<ol>
<li>
<h:outputFormat value="this is param 0 : {0}, param 1 : {1}" >

<f:param value="Number 1" />


<f:param value="Number 2" />
</h:outputFormat>
</li>
<li>
<h:outputFormat value="#{user.text}" >
<f:param value="mkyong" />
</h:outputFormat>
</li>
<li>
<h:outputFormat value="#{user.htmlInput}" >
<f:param value="text" />
<f:param value="size='30'" />
</h:outputFormat>
</li>
<li>
<h:outputFormat value="#{user.htmlInput}" escape="false" >
<f:param value="text" />
<f:param value="size='30'" />
</h:outputFormat>
</li>
<li>
<h:outputFormat value="#{user.htmlInput}" escape="false" >
<f:param value="button" />

<f:param value="value='Click Me'" />


</h:outputFormat>
</li>
</ol>
</h:body>
</html>

Generate following HTML code


<!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">
<body>
<h1>JSF 2.0 h:outputFormat Example</h1>
<ol>
<li>
this is param 0 : Number 1, param 1 : Number 2
</li>
<li>
Hello mkyong
</li>
<li>
&lt;input type=&quot;text&quot; size='30' /&gt;
</li>
<li>

<input type="text" size='30' />


</li>
<li>
<input type="button" value='Click Me' />
</li>
</ol>
</body>
</html>

3. Demo
URL : http://localhost:8080/JavaServerFaces/

2. JSF h:button example

The h:button is a new tag in JSF 2.0, you can declared the navigation outcome directly in the
outcome attribute, no need to call a bean to return an outcome like h:commandButton above.
But, if browsers with JavaScript disabled, the navigation will failed, because the h:button tag is
generate an onclick event to handle the navigation via window.location.href. See examples :
1. Normal button without outcome
//JSF
<h:button value="buton" />

//HTML output
<input type="button"
onclick="window.location.href='/JavaServerFaces/faces/currentpage.xhtml;
return false;"
value="buton" />

P.S if the outcome attribute is omitted, the current page URL will treat as the outcome.
2. Normal button with an outcome
//JSF
<h:button value="buton" outcome="login" />

//HTML output
<input type="button"
onclick="window.location.href='/JavaServerFaces/faces/login.xhtml; return
false;"
value="buton" />

3. Normal button with JavaScript.

//JSF
<h:button value="Click Me" onclick="alert('h:button');" />

//HTML output
<input type="button"

onclick="alert('h:button');window.location.href='/JavaServerFaces/faces/page.x
html;return false;"
value="Click Me" />

My thought
No really sure why JSF 2.0 released this h:button tag, the JavaScript redirection is not practical,
especially in JavaScript disabled browser. The best is integrate the outcome attribute into the
h:commandButton tag, hope it can be done in future release.

1. JSF h:link example


The h:link tag is a new tag in JSF 2.0, the value attribute is rendered as the anchor text,
outcome attribute is determined the target URL of the HTML href attribute. See examples :
1. link + outcome
//JSF
<h:link value="Login page" outcome="login" />

//HTML output
<a href="/JavaServerFaces/faces/login.xhtml">Login page</a>

2. link + outcome + parammeter


//JSF

<h:link value="Login page + Param " outcome="login" >


<f:param name="username" value="mkyong" />
</h:link>

//HTML output
<a href="/JavaServerFaces/faces/login.xhtml?username=mkyong">Login page +
Param</a>

3. link + outcome + image


//JSF
<h:link outcome="login" >
<h:graphicImage library="images" name="sofa.png" />
</h:link>

//HTML output
<a href="/JavaServerFaces/faces/login.xhtml">
<img src="/JavaServerFaces/faces/javax.faces.resource/sofa.png?
ln=images" />
</a>

2. JSF h:commandLink example


The h:commandLink tag is released since JSF 1.x, which is generate a link act like a submit
button when clicked. The value attribute is rendered as the anchor text, action attribute is
determined the target URL of the HTML href attribute. In addition, the h:commandLink will include
a jsf.js file in the page and attached an onclick event to the generated link, see examples :
Note
The j_idtx is a random value generated by JSF.

1. commandLink
//JSF
<h:commandLink value="Login page" />

//HTML output
<script type="text/javascript"
src="/JavaServerFaces/faces/javax.faces.resource/jsf.js?
ln=javax.faces&amp;stage=Development">
</script>

<a href="#"
onclick="mojarra.jsfcljs(document.getElementById('j_idt6'),
{'j_idt6:j_idt16':'j_idt6:j_idt16'},'');
return false">
Login page
</a>

P.S if the action attribute is omitted, it will reload current page while the button is clicked.
2. commandLink + action
//JSF
<h:commandLink action="#{user.goLoginPage}" value="Login page" />

//HTML output
<script type="text/javascript"

src="/JavaServerFaces/faces/javax.faces.resource/jsf.js?
ln=javax.faces&amp;stage=Development">
</script>

<a href="#"
onclick="mojarra.jsfcljs(document.getElementById('j_idt6'),
{'j_idt6:j_idt18':'j_idt6:j_idt18'},'');
return false">
Login page
</a>

P.S You cant even find the action value in the HTML output, only JSF will know where it goes.
3. commandLink + action + parameter
//JSF
<h:commandLink action="#{user.goLoginPage}" value="Login page + Param ">
<f:param name="username" value="mkyong" />
</h:commandLink>

//HTML output
<script type="text/javascript"
src="/JavaServerFaces/faces/javax.faces.resource/jsf.js?
ln=javax.faces&amp;stage=Development">
</script>

<a href="#"

onclick="mojarra.jsfcljs(document.getElementById('j_idt6'),
{'j_idt6:j_idt20':'j_idt6:j_idt20','username':'mkyong'},'');
return false">
Login page + Param
</a>

4. commandLink + action + image


//JSF
<h:commandLink action="#{user.goLoginPage}">
<h:graphicImage library="images" name="sofa.png" />
</h:commandLink>

//HTML output
<script type="text/javascript"
src="/JavaServerFaces/faces/javax.faces.resource/jsf.js?
ln=javax.faces&amp;stage=Development">
</script>

<a href="#"
onclick="mojarra.jsfcljs(document.getElementById('j_idt6'),
{'j_idt6:j_idt23':'j_idt6:j_idt23'},'');
return false">
<img src="/JavaServerFaces/faces/javax.faces.resource/sofa.png?
ln=images" />
</a>

3. JSF h:outputLink example


The h:outputLink tag is released in JSF 1.x, the body of the tag is rendered as the anchor text,
value attribute is rendered as the value of the HTML href attribute directly, see examples :
1. outputLink
//JSF
<h:outputLink>Login page</h:outputLink>

//HTML output
<a href="currentpage.xhtml">Login page</a>

P.S if the value attribute is omitted, it will put the current page URL as the value of the href
attribute.
2. outputLink + value
//JSF
<h:outputLink value="login.xhtml" >
Login page
</h:outputLink>

//HTML output
<a href="login.xhtml">
Login page
</a>

3. outputLink + value + outputText + parameter


//JSF

<h:outputLink value="login.xhtml">
<h:outputText value="Login page" />
<f:param name="username" value="mkyong" />
</h:outputLink>

//HTML output
<a href="login.xhtml?username=mkyong">Login page</a>

4. outputLink + value + outputText + image


//JSF
<h:outputLink value="login.xhtml">
<h:graphicImage library="images" name="sofa.png" />
</h:outputLink>

//HTML output
<a href="login.xhtml">
<img src="/JavaServerFaces/faces/javax.faces.resource/sofa.png?
ln=images" />
</a>

My thought
Some review of above three link tags :
1.

The h:link tag is useful to generate a link which requires to interact with the JSF
outcome , but lack of action support make it hard to generate a dynamic outcome.

2.

The h:commandLink tag is suck, the generated JavaScript is really scary! Not recommend
to use this tag, unless you have a solid reason to support. But it supports the action attribute,
which is what h:link lack of.

3.

The h:outputLink is useful to generate a link which does not require to interact with the
JSF program itself.

At last, it will be perfect if the action attribute is added into the h:link.
In JSF , h:panelGrid tag is used to generate HTML table tags to place JSF components in rows
and columns layout, from left to right, top to bottom.
For example, you used to group JSF components with HTML table tags like this :
HTML
<table>
<tbody>
<tr>
<td>
Enter a number :
</td>
<td>
<h:inputText id="number" value="#{dummy.number}"
size="20" required="true"
label="Number" >
<f:convertNumber />
</h:inputText>
</td>
<td>
<h:message for="number" style="color:red" />

</td>
</tr>
</tbody>
</table>

With h:panelGrid tag, you can get the same table layout above, without typing any of the HTML
table tags :
h:panelGrid
<h:panelGrid columns="3">

Enter a number :

<h:inputText id="number" value="#{dummy.number}"


size="20" required="true"
label="Number" >
<f:convertNumber />
</h:inputText>

<h:message for="number" style="color:red" />

</h:panelGrid>

Note
The column attribute is optional, which define the number of columns are required to lay out the
JSF component, defaults to 1.

h:panelGrid example
A JSF 2.0 example to show you how to use the h:panelGrid tag to lay out the components
properly.

1. Managed Bean
A dummy bean for demo.
package com.mkyong;

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name="dummy")
@SessionScoped
public class DummyBean implements Serializable{

int number;

public int getNumber() {


return number;
}

public void setNumber(int number) {


this.number = number;

2. JSF Page
A JSF XHTML page to use h:panelGrid tag to places JSF components in 3 columns layout.
<?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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jsp/jstl/core"
>
<h:body>

<h1>JSF 2 panelGrid example</h1>

<h:form>
<h:panelGrid columns="3">

Enter a number :

<h:inputText id="number" value="#{dummy.number}"


size="20" required="true"
label="Number" >
<f:convertNumber />
</h:inputText>

<h:message for="number" style="color:red" />

</h:panelGrid>

<h:commandButton value="Submit" action="result" />

</h:form>
</h:body>
</html>

Output following HTML result :


<?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">

<body>
<h1>JSF 2 panelGrid example</h1>

<form id="j_idt6" name="j_idt6" method="post"


action="/JavaServerFaces/faces/default.xhtml"
enctype="application/x-www-form-urlencoded">
<input type="hidden" name="j_idt6" value="j_idt6" />

<table>
<tbody>
<tr>
<td>
Enter a number :
</td>
<td>
<input id="j_idt6:number" type="text"
name="j_idt6:number" value="0" size="20" />
</td>
<td></td>
</tr>
</tbody>
</table>

<input type="submit" name="j_idt6:j_idt10" value="Submit" />


<input type="hidden" .... />
</form>
</body>

</html>

3. Demo
Screen shot of this example.

In JSF, you can output message via following two messages tags :
1.

h:message Output a single message for a specific component.

2.

h:messages Output all messages in current page.

See following JSF 2.0 example to show the use of both h:message and h:messages tags to
display the validation error message.
JSF page
<?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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
>

<h:body>

<h1>JSF 2 message + messages example</h1>

<h:form>

<h:messages style="color:red;margin:8px;" />

<br />

<h:panelGrid columns="3">

Enter your username :

<h:inputText id="username" value="#{user.username}"


size="20" required="true"
label="UserName" >
<f:validateLength minimum="5" maximum="10" />
</h:inputText>

<h:message for="username" style="color:red" />

Enter your age :


<h:inputText id="age" value="#{user.age}"

size="20" required="true"
label="Age" >
<f:validateLongRange for="age" minimum="1"
maximum="200" />
</h:inputText>

<h:message for="age" style="color:red" />

</h:panelGrid>

<h:commandButton value="Submit" action="result" />

</h:form>

</h:body>
</html>

Heres the output

n JSF, f:param tag allow you to pass a parameter to a component, but its behavior is different
depends on which type of component its attached. For example,

1. f:param + h:outputFormat
If attach a f:param tag to h:outputFormat, the parameter is specifies the placeholder.
<h:outputFormat value="Hello,{0}. You are from {1}.">
<f:param value="JSF User" />
<f:param value="China" />
</h:outputFormat>

Heres the output Hello JSF User. You are from China.

2. f:param + Other Component


If you attach a f:param tag to other components like h:commandButton , the parameter is turned
into request parameter.
<h:commandButton id="submitButton"

value="Submit - US" action="#{user.outcome}">


<f:param name="country" value="China" />
</h:commandButton>

In user bean, you can get back the parameter value like this :
Map<String,String> params =
FacesContext.getExternalContext().getRequestParameterMap();

String countrry = params.get("country");

JSF f:param example


Heres a JSF 2.0 application, to show the use of f:param tag in both h:commandButton and
h:outputFormat componenets.

1. Managed Bean
A simple managed bean.
UserBean.java
package com.mkyong;

import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import javax.faces.context.FacesContext;

@ManagedBean(name="user")
@SessionScoped
public class UserBean{

public String name;


public String country;

public String outcome(){

FacesContext fc = FacesContext.getCurrentInstance();
this.country = getCountryParam(fc);

return "result";
}

//get value from "f:param"


public String getCountryParam(FacesContext fc){

Map<String,String> params =
fc.getExternalContext().getRequestParameterMap();
return params.get("country");

//getter and setter methods

2. JSF Page
Two JSF pages for demonstration.
default.xhtml
<?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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
>

<h:body>

<h1>JSF 2 param example</h1>

<h:form id="form">

Enter your name :

<h:inputText size="10" value="#{user.name}" />

<br /><br />

<h:commandButton id="submitButton"
value="Submit - US" action="#{user.outcome}">

<f:param name="country" value="United States" />

</h:commandButton>

</h:form>

</h:body>
</html>

result.xhtml
<?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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
>

<h:body>

<h1>JSF 2 param example</h1>

<h3>
<h:outputFormat value="Hello,{0}. You are from {1}.">
<f:param value="#{user.name}" />
<f:param value="#{user.country}" />
</h:outputFormat>
</h3>

</h:body>

</html>

3. Demo
Enter your name, e.g mkyong, and click on the button.

Display the formatted message, name from user input, country from button parameter.

In JSF, f:attribute tag allow you to pass a attribute value to a component, or a parameter to a
component via action listener. For example,
1. Assign a attribute value to a component.
<h:commandButton">
<f:attribute name="value" value="Click Me" />
</h:commandButton>

//is equal to

<h:commandButton value="Click Me" />

2. Assign parameter to a component and get it back via action listener.


<h:commandButton actionListener="#{user.attrListener}" >
<f:attribute name="username" value="mkyong" />
</h:commandButton>
@ManagedBean(name="user")
@SessionScoped
public class UserBean{

//action listener event


public void attrListener(ActionEvent event){

nickname =
(String)event.getComponent().getAttributes().get("username");

JSF f:attribute example


Ok, lets see a full example in JSF 2.0.

1. Managed Bean
A managed bean named user, with an action listener method.
package com.mkyong;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ActionEvent;

@ManagedBean(name="user")
@SessionScoped
public class UserBean{

public String nickname;

//action listener event


public void attrListener(ActionEvent event){

nickname =
(String)event.getComponent().getAttributes().get("username");

public String outcome(){


return "result";
}

public String getNickname() {


return nickname;
}

public void setNickname(String nickname) {


this.nickname = nickname;
}
}

2. JSF Page
JSF pages to show the use of f:attribute tag to pass a attribute value to a h:commandButton
component.
default.xhtml
<?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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
>

<h:body>

<h1>JSF 2 attribute example</h1>

<h:form id="form">

<h:commandButton action="#{user.outcome}"
actionListener="#{user.attrListener}" >

<f:attribute name="username" value="mkyong" />


<f:attribute name="value" value="Click Me" />

</h:commandButton>

</h:form>

</h:body>
</html>

result.xhtml

<?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://java.sun.com/jsf/html"
>

<h:body>

<h1>JSF 2 attribute example</h1>

#{user.nickname}

</h:body>

</html>

3. Demo
Heres the result.

In JSF, f:setPropertyActionListener tag is allow you to set a value directly into the property of
your backing bean. For example,
<h:commandButton action="#{user.outcome}" value="Submit">

<f:setPropertyActionListener target="#{user.username}" value="mkyong" />


</h:commandButton>

In above JSF code snippets, if the button is clicked, it will set the mkyong value to the username
property viasetUsername() method.
@ManagedBean(name="user")
@SessionScoped
public class UserBean{

public String username;

public void setUsername(String username) {


this.username = username;
}

JSF f:setPropertyActionListener example


Ok, lets see a full example in JSF 2.0.

1. Managed Bean
A super simple managed bean named user.
package com.mkyong;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name="user")
@SessionScoped
public class UserBean{

public String username;

public String outcome(){


return "result";
}

public String getUsername() {


return username;
}

public void setUsername(String username) {


this.username = username;
}

2. JSF Page

JSF page to show the use of f:setPropertyActionListener to set a value mkyong directly into the
property username of your backing bean.
default.xhtml
<?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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
>

<h:body>

<h1>JSF 2 setPropertyActionListener example</h1>

<h:form id="form">

<h:commandButton action="#{user.outcome}" value="Click Me">

<f:setPropertyActionListener target="#{user.username}"
value="mkyong" />

</h:commandButton>

</h:form>

</h:body>
</html>

result.xhtml
<?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://java.sun.com/jsf/html"
>

<h:body>

<h1>JSF 2 setPropertyActionListener example</h1>

#{user.username}

</h:body>

</html>

3. Demo
Heres the result after button is clicked.

In JSF, h:dataTable tag is used to display data in a HTML table format. The following JSF 2.0
example show you how to use h:dataTable tag to loop over an array of order object, and display
it in a HTML table format.

1. Project Folder
Project folder structure of this example.

2. Managed bean
A managed bean named order, initialized the array object for later use.
OrderBean.java
package com.mkyong;

import java.io.Serializable;
import java.math.BigDecimal;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name="order")

@SessionScoped
public class OrderBean implements Serializable{

private static final long serialVersionUID = 1L;

private static final Order[] orderList = new Order[] {

new Order("A0001", "Intel CPU",


new BigDecimal("700.00"), 1),
new Order("A0002", "Harddisk 10TB",
new BigDecimal("500.00"), 2),
new Order("A0003", "Dell Laptop",
new BigDecimal("11600.00"), 8),
new Order("A0004", "Samsung LCD",
new BigDecimal("5200.00"), 3),
new Order("A0005", "A4Tech Mouse",
new BigDecimal("100.00"), 10)
};

public Order[] getOrderList() {

return orderList;

public static class Order{

String orderNo;
String productName;
BigDecimal price;
int qty;

public Order(String orderNo, String productName,


BigDecimal price, int qty) {

this.orderNo = orderNo;
this.productName = productName;
this.price = price;
this.qty = qty;
}

//getter and setter methods


}
}

3. CSS
Create a CSS file to style the table layout.
table-style.css

.order-table{
border-collapse:collapse;
}

.order-table-header{
text-align:center;
background:none repeat scroll 0 0 #E5E5E5;
border-bottom:1px solid #BBBBBB;
padding:16px;
}

.order-table-odd-row{
text-align:center;
background:none repeat scroll 0 0 #FFFFFFF;
border-top:1px solid #BBBBBB;
}

.order-table-even-row{
text-align:center;
background:none repeat scroll 0 0 #F9F9F9;
border-top:1px solid #BBBBBB;
}

4. h:dataTable

A JSF 2.0 xhtml page to show the use of h:dataTable tag to loop over the array of order object.
This example should be self-explanatory.
default.xhtml
<?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://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
>
<h:head>
<h:outputStylesheet library="css" name="table-style.css"

/>

</h:head>
<h:body>

<h1>JSF 2 dataTable example</h1>

<h:dataTable value="#{order.orderList}" var="o"


styleClass="order-table"
headerClass="order-table-header"
rowClasses="order-table-odd-row,order-table-even-row"
>

<h:column>
<!-- column header -->
<f:facet name="header">Order No</f:facet>
<!-- row record -->
#{o.orderNo}
</h:column>

<h:column>
<f:facet name="header">Product Name</f:facet>
#{o.productName}
</h:column>

<h:column>
<f:facet name="header">Price</f:facet>
#{o.price}
</h:column>

<h:column>
<f:facet name="header">Quantity</f:facet>
#{o.qty}
</h:column>

</h:dataTable>

</h:body>
</html>

Generate this HTML output


<!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">
<head>
<link type="text/css" rel="stylesheet"
href="/JavaServerFaces/faces/javax.faces.resource/tablestyle.css?ln=css" />
</head>
<body>

<h1>JSF 2 dataTable example</h1>

<table class="order-table">

<thead>
<tr>
<th class="order-table-header" scope="col">Order No</th>
<th class="order-table-header" scope="col">Product Name</th>
<th class="order-table-header" scope="col">Price</th>
<th class="order-table-header" scope="col">Quantity</th>
</tr>

</thead>

<tbody>
<tr class="order-table-odd-row">
<td>A0001</td>
<td>Intel CPU</td>
<td>700.00</td>
<td>1</td>
</tr>
<tr class="order-table-even-row">
<td>A0002</td>
<td>Harddisk 10TB</td>
<td>500.00</td>
<td>2</td>
</tr>
<tr class="order-table-odd-row">
<td>A0003</td>
<td>Dell Laptop</td>
<td>11600.00</td>
<td>8</td>
</tr>
<tr class="order-table-even-row">
<td>A0004</td>
<td>Samsung LCD</td>

<td>5200.00</td>
<td>3</td>
</tr>
<tr class="order-table-odd-row">
<td>A0005</td>
<td>A4Tech Mouse</td>
<td>100.00</td>
<td>10</td>
</tr>
</tbody>
</table>
</body>
</html>

6. Demo
URL : http://localhost:8080/JavaServerFaces/default.xhtml

You might also like