JSF Tutorial: Common Used Jsf Tags
This Tutorial is the 2nd part of JSf tutorials.
If not please go through this tutorial. This tutorial assums that you have downloaded the sample jsf application from the beginners tutorial and have deployed it successfully.
1. h:outputText
–This is the simplest jsf component. It outputs bean properties.
– NAME generated automatically or we can Specify it.
– VALUE of form #{beanName.propertyName} poperty can be of any primitive data types as int,folat,double,String orit can be Wrapper Type objects like Integer,Float etc.
2. h:inputText
The attributes are:
– NAME generated automatically or we can Specify it.
– VALUE of form #{beanName.propertyName} poperty can be of any primitive data types as int,folat,double,String orit can be Wrapper Type objects like Integer,Float etc.
Usage:
In managed bean have following:
String var = “Good Morning!”;
public void getVar(){ return var;}
public void setVar(String var){ this.var = var;}
Useful Hint : If you don’t know this: If you are using eclipse, you can easily generate getter and setter methods. Just place cursor inside the class. Click source(on top menu) -> select ‘Generate getters and setters’.
Now in jsp file you can have:
<f:view> <h:form> <h:inputText value=”#{managed_bean.var}” /> <br /> <h:outputTest value=”You just entered: #{managed_bean.var}” /> <br /> <h:commandButton action=”” value=”Click me to see output” /> </h:form> </f:view>
Now run the jsf and you can see the entered value displaying
3. h:inputSecret
- This is used for hiding the input text like a password field. Used same as inputText .
– Name generated automatically or we can Specify it.
– Value applies only to output, not input
4. h:commandButton
This component is similar to <submit type=”submit”> of HTML. It will submit the jsf form. The h:commandButton has an advantage that you can specify which java method to call when page submits. You can specify this using the action attribute. This will be called after all the page data is saved using the setter methods. It you want to skip the setter methods, you can use immediate=”true” attribute. This will directly call the function, without setting any page’s variables.
For example: You have a Bean for user profile edit something like below:
Public class UserEditBean{
private String name;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String saveData(){
if(getName() == null || getName().trim().equals(“”)){
FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR, “Name Required!”,”Please Enter UserName”));
return “error”;
}
if(getPassword() == null || getPassword().trim().equals(“”)){
FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR, “Password Required!”,”Please Enter Password”));
return “error”;
}
//else save data
return “success”;
}
public String cancelPage(){
return “cancel”;
}
}
Create a page with <h:inputText> for name and pwd and a h:commandButton as below
<f:view>
<h:form>
<h:messages />
Name : <h:inputText value=”#{managed_bean.name}” /> <br />
Password: <h:outputTest value=”You just entered: #{managed_bean.password}” />
<br />
<h:commandButton action=”saveData” value=”Save” />
<h:commandButton action=”cancelPage” value=”Cancel” immediate=”true”/>
</h:form>
</f:view>
Here saveData will be called after all setter methods for page fields like name and pwssword field are called. In cancel button when we have immediate=”true” none of the setter method is called and cancelPage() will be called directly.
The attribute list are:
– name generated automatically or we can Specify it.
– value is the Label of the button displayed in the frontend.
– actionListener Listener method to fire when form submitted.
Action listeners are one which will be called before calling action functions.
5 Check boxes: h:selectBooleanCheckbox
It uses Boolean type to store data. If you want to use a h:selectBooleanCheckbox in your page, first declare a corresponding Boolean variable in the bean something like below:
Boolean chkBooleanBox;
public Boolean getChkBooleanBox() {
return chkBooleanBox;
}
public void setChkBooleanBox(Boolean chkBooleanBox) {
this.chkBooleanBox = chkBooleanBox;
}
Assign value to a boolean bean property. Value always set to true or false
Add following to your jsp page:
<f:view>
<h:form>
<h:outputText value=”This is Boolean checkbox Example:” /> :
<h:selectBooleanCheckbox value=”#{personBean.chkBooleanBox}”></h:selectBooleanCheckbox> <br/>
<h:outputText value=”Have a Nice Day!!!” rendered=”#{personBean.chkBooleanBox}” /> <br/>
<br />
<h:commandButton action=”” value=”Click me to see output” />
</h:form>
</f:view>
When you run it you will see ‘Have a Nice Day’ only if you checked checkbox.
Adding valueChangeListener:
If your goal is to do some action if the checkbox is checked or unchecked and as soon as page is submitted, then you can add valueChangeListener to it. The action listener will be called as soon as the page submits (but after setter methds are called) but before any action method on button called.
Eg in the above example replace : selectBooleanCheckbox with the following:
<h:selectBooleanCheckbox value=”#{personBean.chkBooleanBox}” valueChangeListener=”#{ personBean.addToSelectedList}” ></h:selectBooleanCheckbox>
Then the addToSelectedList will be called before the command buttons action method is called but after all setter method.
public void addToSelectedList(ValueChangeEvent event) {
// get more information about envent and button
// we can use this to add selected items to a common place (like //shopping carts
}
The common attributes are:
– action : Action controller method to fire when form submitted. Runs after all listeners have completed.
– name generated automatically or we can Specify it.
– value is the Label of the button displayed in the frontend.
– actionListener = Listener method to fire when form submitted.
– immediate = Indicates that setter methods and validation is bypassed
• Usually used with actionListener
6. Comboboxes
– h:selectOneMenu
– h:selectManyMenu
These are bit complex tags than other tags. These tags have 2 parts:
- the select Items : which populates the possible options in the menu or dropdown (similar to <option> tag of html)
- The value: which saves the user input.
The possible dropdown options should be encapsulated in a special objects called SelectItem(javax.faces.model.SelectItem).A simple example is shown below: Include following in your bean:
String selectedState;
public String getSelectedState() {
return selectedState;
}
public void setSelectedState(String selectedState) {
this.selectedState = selectedState;
}
The jsp page willbe
<f:view>
<h:form>
<h:outputText value=”Please select your state:” /> :
<h:selectOneMenu value=”#{personBean.selectedState}”>
<f:selectItem itemValue=”MH” itemLabel=”Maharashtra”/>
<f:selectItem itemValue=”KA” itemLabel=”Karnataka”/>
<f:selectItem itemValue=”KE” itemLabel=”Kerala”/>
<f:selectItem itemValue=”AP” itemLabel=”Andrapradesh”/>
<f:selectItem itemValue=”GJ” itemLabel=”Gujrat”/>
</h:selectOneMenu>
<br />
<h:commandButton action=”” value=”Click me to see output” />
<br />
<h:outputText value=”You have selected #{personBean.selectedState}”/>
</h:form>
</f:view>
You will see the selected state down when you click the button. You can also construct the possible options to the dropdown and save it in a List, which you can display using <f:selectItems> tag
Eg: In bean create a ArrayList of SelectItems
Import javax.faces.model.SelectItem;
private List< SelectItem> options = new ArrayList< SelectItem>();
public List<SelectItem> getOptions() {
options.add(new SelectItem(“MH”,” Maharashtra”));
options.add(new SelectItem(“KA”,” Karnataka”));
options.add(new SelectItem(“KE”,” Kerala”));
options.add(new SelectItem(“Ap”,” Andrapradesh”));
options.add(new SelectItem(“GJ”,” Gujrat”));
return options;
}
public void setOptions(List<SelectItem> options) {
this.options = options;
}
The jsp page change is :
<h:selectOneMenu value=”#{personBean.selectedState}”>
<f:selectItems value=”#{personBean.options}”/>
</h:selectOneMenu>
Using h:selectManyMenu:
In this case the selected values will be stored in the specified array.So we have to specify a List / array in the value field to the <h:selectManyMenu> tag
Add following tags to jsp:
<h:outputText value=”How many pets you have?:” /> :
<h:selectManyMenu value=”#{personBean.selectedInts}”>
<f:selectItems value=”#{personBean.items}”/>
</h:selectManyMenu>
Add following lines to PersonBean:
Here we have used new tag <f:selectItems> which takes any collection/array of SelectItems to build the options.We build a List of SelectItems in constructore as shown below. We store selected values in selectedInts Integer array:
Integer[] selectedInts = new Integer[5];
List<SelectItem> items = new ArrayList<SelectItem>();
public PersonBean(){
items.add(new SelectItem(new Integer(1),”One”));
items.add(new SelectItem(new Integer(2),”Two”));
items.add(new SelectItem(new Integer(3),”Three”));
items.add(new SelectItem(new Integer(4),”Four”));
items.add(new SelectItem(new Integer(4),”Five”));
}
public Integer[] getSelectedInts() {
return selectedInts;
}
public void setSelectedInts(Integer[] selectedInts) {
this.selectedInts = selectedInts;
}
public List<SelectItem> getItems() {
return items;
}
public void setItems(List<SelectItem> items) {
this.items = items;
}
**
Add following imports:
import java.util.List;
import java.util.ArrayList;
import javax.faces.model.SelectItem;
Similarly h:selectManyListbox Tag will be used.(Advantage is it has size tag using which more options will be visible unlike the SelectManyMenu where only one option is visible)
ListBoxes: There are 2 options.
– h:selectOneListbox
– h:selectManyListbox
These will be used Same way as h:selectOneMenu and h:selectManyMenu
7 Radio Buttons
– h:selectOneRadio tag is used to display a radio button. They also user SelectItem to display possible radio options.
inputName.jsp:
Gender:
<h:outputText value=”#{personBean.gender}”></h:outputText>
PersonBean
String gender;
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
geeting.jsp
Gender:
<h:outputText value=”#{personBean.gender}”></h:outputText>
8. DataTables:
Helps displaying collections in tabular format. This iterates through a Collection automatically and displays the data in tabular format.
We give one row definition, and JSF repeats it
<h:dataTable value=”#{someBean.someCollection}”
var=”rowVar”
border=”1″>
<h:column>
<h:outputText value=”#{rowVar.col1Data}”/>
</h:column>
<h:column>
<h:outputText value=”#{rowVar.col2Data}”/>
</h:column>
…
</h:dataTable>
Some feature are:
• Can enclose other h:Xxxx elements
– h:outputText, h:inputText, etc.
• Regular HTML must be enclosed in f:verbatim
<h:column>
<f:verbatim>First Name: </f:verbatim>
<h:outputText value=”#{rowVar.firstName}”/>
</h:column>
• Table headings and footers specified with f:facet
Example:
Create following Student Bean.
package jsfks;
public class StudentBean {
String name;
String grade;
Double score;
public StudentBean(String name,String grade,double score){
this.name= name;
this.grade = grade;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public Double getScore() {
return score;
}
public void setScore(Double score) {
this.score = score;
}
}
Create StudentsActionBean:
package jsfks;
import java.util.List;
import java.util.ArrayList;
public class StudentsActionBean {
List<StudentBean> students = new ArrayList<StudentBean>();
public StudentBean(){
}
public StudentsActionBean(){
students.add(new StudentBean(“Amita”,”IIXth”,80.4));
students.add(new StudentBean(“Arpita”,”IIXth”,60.1));
students.add(new StudentBean(“Gagan”,”IIXth”,88.5));
students.add(new StudentBean(“Kiran”,”IIXth”,89.8));
students.add(new StudentBean(“Mamatha”,”IIXth”,90.00));
students.add(new StudentBean(“Yogita”,”IIXth”,84.00));
}
public List<StudentBean> getStudents() {
return students;
}
public void setStudents(List<StudentBean> students) {
this.students = students;
}
}
Make an entry in facesConfig.xml:
<managed-bean>
<managed-bean-name>studentsActionBean</managed-bean-name>
<managed-bean-class>jsfks.StudentsActionBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
Create jsp page
ataTableJsp.jsp
<%@ taglib uri=”http://java.sun.com/jsf/html” prefix=”h” %>
<%@ taglib uri=”http://java.sun.com/jsf/core” prefix=”f” %>
<html>
<head>
<title>Datatable example</title>
</head>
<body>
<f:view>
<h:form>
<h1> Student Information </h1>
<h:dataTable value=”#{studentsActionBean.students}” var=”student” border=”1″>
<h:column>
<f:facet>
<h:outputText value=”Name” />
</f:facet>
<h:outputText value=”#{student.name}” />
</h:column>
<h:column>
<f:facet>
<h:outputText value=”Grade” />
</f:facet>
<h:outputText value=”#{student.grade}” />
</h:column>
<h:column>
<f:facet>
<h:outputText value=”Score” />
</f:facet>
<h:outputText value=”#{student.score}” />
</h:column>
</h:dataTable>
</h:form>
</f:view>
</body>
</html>
Here <f:facet>
<h:outputText value=”Name” />
</f:facet>
Defines table headings.
Following attributes to h:dataTable element helps in formatting table:
– rowClasses: comma-separated list of CSS styles. Applied
to each row until list ends, then repeats
– headerClass: CSS style for heading
– footerClass: CSS style for footer









Nice Article. Keep up the good work…