You are on page 1of 146

Java Server Faces (JSF)

JSF
• JavaServer Faces (JSF) is a Java-based web
application framework intended to simplify
development integration of web-based user interfaces.
JSF
• JavaServer Faces (JSF) is a MVC web framework that
simplifies the construction of user interfaces (UI) for
server-based applications by using reusable UI
components in a page.
• JSF provides facility to connect UI widgets with data
sources and to server-side event handlers.
• The JSF specification defines a set of standard UI
components and provides an Application Programming
Interface (API) for developing components.
• JSF enables the reuse and extension of the existing
standard UI components.
Benefits of JSF
• JSF reduces the effort in creating and maintaining
applications which will run on a Java application
server and will render application UI on to a target
client.
• JSF facilitates Web application development by
– providing reusable UI components
– making easy data transfer between UI components
– managing UI state across multiple server requests
– enabling implementation of custom components
– wiring client side event to server side application code
JSF UI component model
• JSF provides developers capability to create Web application
from collections of UI components that can render themselves
in different ways for multiple client types (for example HTML
browser, wireless or WAP device).
• JSF provides
– Core library
– A set of base UI components - standard HTML input elements
– Extension of the base UI components to create additional UI
component libraries or to extend existing components.
– Multiple rendering capabilities that enable JSF UI components to
render themselves differently depending on the client types
Features of JSF
• Provides easy-to-use environment i.e. IDE for
developing web application with JSF UI components.
• Manage all UI components in a web page. Managing
UI components includes validation of user input, state
of component, page navigation and event handling.
• Can customize and reuse JSF UI components.
• Supports multiple client devices. There are different
renderers to make same UI component to be
displayed for different client devices.
Features of JSF
• Contains components that support internationalization
and enable displaying localized messages according to
the specified Locale.
• Supports a standard Rapid Application
Development(RAD) Java Web application framework,
which enables fast development of a powerful
application with a set of reusable components.
• Provides extensible architecture, which means that you
can add other functionalities over JSF and can easily
customize and reuse JSF UI components.
MVC Architecture
• JSF implements MVC Design Pattern.
MVC Architecture of JavaServer Faces
JSF Architecture
• The controller part of JSFarchitecture consists of a controller
servlet, that is, FacesServlet, a centralized configuration file,
faces-config.xml, and a set of event handlers for the web
application.
• The Front controller (FacesServlet) receives all the requests
and manages the request processing life cycle of each request
to generate response for the client.
• On the basis of the results of component events, the flow of
application’s pages is also controlled by the FacesServlet.
• The FacesServlet manages client requests by referencing the
page mappings provided in the faces-config.xml file.
JSF Architecture
• The Model in JSF architecture is a set of server-side
Javabeans that retrieves the values from the model
components, such as the database and defines methods on
the basis of these values.
• These Java beans may further persists in a database
through an underlying persistence layer, such as Java data
objects, Enterprise Javabeans, or an object-relational
mapping implementation, such as hibernate.
JSF Architecture
• The view in JSF architecture comprises stateful UI
components.
• The UI components are rendered in different ways
according to the type of the client.
• The view delegates this task to separate the renderers,
each taking care of one specific output type, such as
HTML or Wireless Markup Language(WML).
• Can also attach various additional delegates such as
validators and converters to specific components.
JSF Request Processing Life Cycle
• Request lifecycle consists of 6 phases:
– Restore View Phase
– Apply Request Values Phase
– Process Validations Phase
– Update Model Values Phase
– Invoke Application Phase
– Render Response Phase
• The execution of all these phases is not required for a given
request.
• The request processing life cycle can be terminated in any
phase by executing FacesContext.responseComplete() method.
Request Lifecycle Diagram
Restore View Phase
• A view can be defined as a collection of components in a
request page.
• All the components in a request page or view are grouped
together as a tree.
• Every view is a tree of components having a unique
identification, i.e. view ID.
• The JSF controller servlet finds the view ID from the
request, which can be determined by the requested JSP
page name.
• The controller can load the existing view or can create a
new view if it does not exist.
Restore View Phase
• Restore view phase can handle three different views:
– New view
– Initial view
– postback
• In case of New view, this phase creates the view of the request page and
associates event handlers and validators to the components in the view.
• This phase also stores the view as root component using setViewRoot()
method on FacesContext instance.
• When the JSF is requested for the first time, the view needs to be loaded
for the first time(initial view) and the controller creates an empty view.
• In case of initial view, the framework directly moves to render the
response page.
• If the user requests a page accessed earlier (postback), the controller
needs to restore the view with the current state of the view.
Apply Request Values Phase
• In this phase, JSF implementation iterates the component objects in
the component tree and requests every component to decode itself.
• Decoding is the process in which the framework sets the submitted
values for the components based on the request parameters.
• The component value can be validated in this phase if the immediate
property is true for the component.
• In case of validation error, an error message is added and the render
response phase starts.
• If the immediate property of the component is set to false, then the
submitted string values are converted into the desired data type.
• At the end of this phase, each component stores recent values
submitted through current request. After the completion of this
phase, the existing events are broadcasted for the associated event
listeners.
Process Validations Phase
• In this phase, the values of all components are validated against
some validation rules.
• A component can be associated with some JSF standard validator or
can define our own validators.
• The validators are registered with the components of the JSF page.
• In case of validation error, an error message is added and the render
response phase starts.
<h:inputText label=“Name” id=“name” value=“#{student.name}”
required=“true” valueChangeListener=“#{student.change}”>
<f:validateLength minimum=“2” maximum=“25” />
</h:inputText>
If all the submitted values are found valid, the framework enters into
the update model values phase of the life cycle.
Update Model Values Phase
• After validating component values, all values of the backing
beans or model objects are updated with the component values
to save the state of components so that these values can be
used in subsequent requests.
• Every component can be associated with some backing bean
property and the backing bean is updated with the current
value of the component.

<h:inputText label=“Name” id=“name”


value=“#{student.name}” required=“true” >
</h:inputText>
Invoke Application Phase
• In this phase, the JSF framework broadcasts all the added action
events, which are further handled by the registered action event
listeners.
• Some backing bean methods can be registered as action listeners or
action methods.
• The action method may contain the logic for different operations,
such as rendering responses and adding messages.
• Action methods are also integrated with the navigation model and
helps in determining the next view or page to be displayed.
• After the completion of all phases and handling of all events by the
respective listeners, the framework is ready with the next view for
the user.
Render Response Phase
• This phase is responsible for sending responses to the client.
• The state of the view is saved in this phase before the response
is rendered for the client.
• The state of the view can be stored on server side using client
session or can be saved on client side using hidden fields.
• During this phase, all component values are converted into a
string to be displayed. When this phase completes, the web
container sends the response to the client as a response page in
browser.
JSF Elements
• UI Component
• Renderer
• Validator
• Backing Beans
• Converter
• Events & Listeners
• Message
• Navigation
UI Component
• UI components are the basic reusable components for
developing UIs using the JSF framework.
• Server communicates with the client through these UI
components.
• These components are simple JavaBeans containing
properties, methods, and events.
• JSF UI componets are stateful UI components.
• All UI components are organized as a component tree
and are usually displayed as a JSF page.
UI Components
Renderer
• JSF introduces renderer, which completely separate the functionality of a component
from the presentation logic on the client-side.
• JSF supports two types of rendering:
– Direct Rendering Model
• A JSF UI component is capable of rendering itself.
• Rendering logic is directly encapsulated into the UI components. No clear
separation of functionality and presentation.
– Indirect/Delegated Rendering Model
• A separate class known as renderer handles the process of rendering.
• Renderer class is responsible for encoding, which is the process of creating the
presentation of UI components in some markup language for the given client.
<h:inputText label=“Name” id=“name” required=“true”/>
When a component is rendered and the response is created for the HTML client,
the following HTML code lines are sent to the client browser
<input type=“text” id=“myForm:name” name=“myForm:name” />
Validators
• The data entered by client in UI components must be validated for its correctness
according to the defined range and format.
• We can use Java script or Java for writing validation logic, either on client side or on
server side according to its complexity.
• While working with JSF components, the Java code is not required to validate the
input data.
• JSF can handle the validation of data in the following three different ways:
– Implementing validation inside the UI component
– Using validator method in backing beans
– Using validator classes
• When validation logic is written using first way, the validation will be done for only
that component and not for other components of the form.
• When validation logic is written using second method, the validation will be done
for one or more fields of the form, but other components cannot use it.
• When validation is written in validator classes, it provides validation for generic
cases, such as validating a field for allowed length of string or for an allowed
number range.
– E.g. <h:inputText label=“Name” id=“name” required=“true”>
<f:validateLength minimum=“2” maximum=“25”/>
</h:inputText>
Backing Beans
• The model part in backing beans contain business logic and data.
• In a JSF application, there are some JavaBean objects, which handle or store
data between the business model and UI component at intermediate stage.
These JavaBean objects are known as Backing Beans.
• Backing beans play the role of controller by handling the interaction between
view and the Model.
• Backing beans contain properties and event listener methods for storing and
manipulating the user’s data.
• The event listener methods can also manipulate the UI or execute the
application logic in the back end.
• We can also associate a UI component with the property of backing bean
through EL value logic in the backend.
• We can also bind the method of backing beans with some UI action
component to process the logic.
• <h:inputText label=“Name” id=“name” value=“#{student.name}”
required=“true” />
Backing Beans
• We can configure a backing bean in faces-config.xml file and define the
name of the object, the class to be, and the scope of that object.
• The beans that are configured also known as Managed Beans.
• Therefore, all backing beans are managed beans.
• <managed-bean>
<managed-bean-name>student</managed-bean-name>
<managed-bean-class>com.kogent.Student</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
Converters
• We can enter only a string through a UI component, whereas in
backing bean or in the model layer the data can be any java object.
So, we need a Converter.
• A converter is a translator, which can convert a Java object into a
string and an input string into some java object.
• JSF provides number of converters for common types, such as date
and numbers.
• <h:inputText id=“dob” value=“#{student.dob}”>
<f:convertDateTime type=“date” pattern=“dd-MM-yyyy”/>
</h:inputText>
• The renderers use converters during the process of encoding and
decoding.
• JSF converters also support formatting and localization.
Events and Listeners
• Events generated on different UI components can be mapped
to the execution of a method.
• The JSF event model is based on simple Java Bean’s event
model.
• JSF uses JavaBeans to handle events with event objects and
event listeners.
• A UI component can generate one or more types of events,
and we can register respective event listener with the
component to respond to those events.
• The event listeners further invoke associated backing bean
method to process the appropriate logic.
• <h:inputText id=“empid”
valueChangeListener=“#{employee.valueChanged}” />
Events and Listeners
• JSF defines four different types of standard events:
– Action events
– Value-change events
– Phase events
Action Events
• The UI component which represents a command, can generate action
events.
• A component that can generate an action event is known as an action
source. e.g. HtmlCommandButton
• For handling action events, we can associate an action listener with the
UI component.
• Two types of action listeners
– One that affects navigation
– One that does not affect navigation
• The action listener that does not affect navigation executes the code,
modifies backing bean or application model, and redisplays the current
page.
• The actionlistener, that affects navigation, executes the logic, and
returns the output to navigation model to select the next page to be
displayed to the client.
Action Events
• The action listener, which affects navigation, checks the output of
action method configured with the component responsible for firing
the action event.
• Example:
<h:CommandButton type=“submit” value=“Add Employee”
action=“#{employee.addNew}” />
Public class Employee
{
public String addNew() {
if (…)
return “success”;
else
return “error”;
}}
Action Events
• If we do not want to affect navigation by an action event and just need to
process some logic, you need to configure an action listener method
instead of action method with the component.
<h:CommandButton type=“submit” value=“update”
actionListener=“#{employee.update}” />
public class Employee
{
public void update(ActionEvent e) {

}
}
Value-change Events
Whenever, an end user enters a new value into components such as text box or
text area, a value-change event is fired.
<h:inputText id=“rollno” name=“rollno”
valueChangeListener=“#{student.processValueChange}” />
public class Student
{
public void processValueChange(ValueChangeEvent e) {
HtmlInputText comp=(HtmlInputText)e.getComponent();
}
}
Phase Events
• Every request in a JSF application has a life cycle, which is a set of six
different stages or phases.
• These phases include getting request-based view, obtaining component
values from request parameters, validate user input, update backing bean
and model objects, invoking action listener and returning response back to
the client.
• Each phase has its start point and end point and a single event is fired when
a phase either begins or ends.
• Both events, the event at start point and the event at end point, are known
as phase events.
• Phase events are not fired by any UI component. They are generated by
JSF.
• The listener for a phase event is registered directly with the instance of
javax.faces.lifecycle.LifeCycle, which represents the entire life cycle of
request processing.
Message
• Messages are an integral part of the JSF framework.
• A message is used to inform the user about different errors that can occur
while processing the logic.
• A message may be associated with some component or it can be an
application level message.
• There are two categories of messages:
– Application errors (business logic)
– User input errors (empty text field, invalid input text)
• Different validators can add messages to FacesContext and also provide
different validations.
• In addition to error messages, informational messages can be there.
• HtmlMessage and HtmlMessages are two components used to display
messages.
• <h:message for=“name” style=“color:red” />
Navigation
• JSF provides an efficient way to configure all navigation rules
declaratively in a single location, i.e., faces-config.xml file.

<navigation-rule>
<from-view-id>/login.jsp</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/welcome.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>failure</from-outcome>
<to-view-id>/login.jsp</to-view-id>
</navigation-case>
</navigation-rule>
JSF Expression Language
• JSF provides a rich expression language. We can write normal
operations using #{operation-expression} notation. Some of the
advantages of JSF Expression languages are following.
• Can reference bean properties where bean can be a object stored in
request, session or application scope or is a managed bean.
• Provides easy access to elements of a collection which can be a list,
map or an array.
• Provides easy access to predefined objects such as request.
• Arithmetic, logical, relational operations can be done using
expression language.
• Automatic type conversion.
• Shows missing values as empty strings instead of
NullPointerException.
JSF Expression Language (Example – UserData.java)

import java.io.Serializable;
import java.util.Date;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {
private static final long serialVersionUID = 1L;
private Date createTime = new Date();
private String message = "Hello World!";
public Date getCreateTime()
{ return(createTime); }
public String getMessage()
{ return(message); } }
JSF Expression Language (Example – home.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:head> <title>JSF Tutorial!</title> </h:head>
<h2>Expression Language Example</h2>
Creation time: <h:outputText value="#{userData.createTime}"/>
<br/><br/>
Message: <h:outputText value="#{userData.message}"/>
</h:body>
</html>
First JSF Application

Create a page home.xhtml under webapp folder. Update


the code of home.xhtml as shown below.
<!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>
<title>JSF Tutorial!</title>
</head>
<body> #{helloWorld.getMessage()} </body>
</html>
Create a Managed Bean

package com.tutorialspoint.test;
import javax.faces.bean.ManagedBean;
@ManagedBean(name = "helloWorld", eager = true)
public class HelloWorld {
public HelloWorld()
{ System.out.println("HelloWorld started!"); }

public String getMessage() { return "Hello World!"; }


}
Configure Faces Servlet in web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<welcome-file-list>
<welcome-file>faces/home.xhtml</welcome-file>
</welcome-file-list>
<!-- FacesServlet is main servlet responsible to handle all request.
It acts as central controller. This servlet initializes the JSF
components before the JSP is displayed. -->
Configure Faces Servlet in web.xml
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
Configure Faces Servlet in web.xml
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
</web-app>
Managed Bean
• Managed Bean is a regular Java Bean class registered with JSF. In
other words, Managed Beans is a java bean managed by JSF
framework.
• The managed bean contains the getter and setter methods, business
logic or even a backing bean (a bean contains all the HTML form
value).
• Managed beans works as Model for UI component.
• Managed Bean can be accessed from JSF page.
• In JSF 1.2,a managed bean had to register it in JSF configuration
file such as faces-config.xml.
• From JSF 2.0 onwards, Managed beans can be easily registered
using annotations. This approach keeps beans and there registration
at one place and it becomes easier to manage.
Managed Bean Registration

Using XML Configuration


<managed-bean>
<managed-bean-name>helloWorld</managed-bean-name>
<managed-bean-class>
com.tutorialspoint.test.HelloWorld</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
Managed Bean Registration

Using Annotation
@ManagedBean(name = "helloWorld", eager = true)
@RequestScoped
public class HelloWorld
{ @ManagedProperty(value="#{message}")
private Message message; ... }
@ManagedBean Annotation

• @ManagedBean marks a bean to be a managed bean


with the name specified in name attribute. If the name
attribute is not specified, then the managed bean name
will default to class name portion of the fully qualified
class name. In our case it would be helloWorld.
• Another important attribute is eager. If eager="true"
then managed bean is created before it is requested for
the first time otherwise "lazy" initialization is used in
which bean will be created only when it is requested.
Scope Annotations
Scope Description
@RequestScoped Bean lives as long as the HTTP request-response lives. It get created
upon a HTTP request and get destroyed when the HTTP response
associated with the HTTP request is finished.
@NoneScoped Bean lives as long as a single EL evaluation. It get created upon an EL
evaluation and get destroyed immediately after the EL evaluation.

@ViewScoped Bean lives as long as user is interacting with the same JSF view in the
browser window/tab. It get created upon a HTTP request and get
destroyed once user postback to a different view.
@SessionScoped Bean lives as long as the HTTP session lives. It get created upon the
first HTTP request involving this bean in the session and get destroyed
when the HTTP session is invalidated.
@ApplicationScoped Bean lives as long as the web application lives. It get created upon the
first HTTP request involving this bean in the application (or when the
web application starts up and the eager=true attribute is set in
@ManagedBean) and get destroyed when the web application shuts
down.
@CustomScoped Bean lives as long as the bean's entry in the custom Map which is
created for this scope lives.
@ManagedProperty Annotation

• JSF is a simple static Dependency Injection(DI)


framework.
• Using @ManagedProperty annotation a managed
bean's property can be injected in another managed
bean.
JSF Page Navigation

• Navigation rules are those rules provided by JSF


Framework which describe which view is to be
shown when a button or link is clicked.
• Navigation rules can be defined in JSF configuration
file named faces-config.xml.
• Navigation rules can be defined in managed beans.
• Navigation rules can contain conditions based on
which resulted view can be shown.
• JSF 2.0 provides implicit navigation as well in which
there is no need to define navigation rules as such.
Implicit Navigation
• Auto Navigation in JSF Page
• JSF 2.0 provides auto view page resolver mechanism
named implicit navigation.
• In this case you only need to put view name in action attribute
and JSF will search the correct view page automatically in the
deployed application.
<h:form>
<h3>Using JSF outcome</h3>
<h:commandButton action="page2" value="Page2" /> </h:form>

Here when Page2 button is clicked, JSF will resolve the view


name, page2 as page2.xhtml extension, and find the
corresponding view file page2.xhtml in the current directory.
Auto Navigation in Managed Bean
<h:form>
<h3>Using Managed Bean</h3>
<h:commandButton
Action="#{navigationController.moveToPage1}" value="Page1" />
</h:form>

@ManagedBean(name = "navigationController", eager = true)


@RequestScoped
public class NavigationController implements Serializable {
public String moveToPage1(){ return "page1"; } }
Conditional Navigation
<h:form>
<h:commandLink action="#{navigationController.showPage}"
value="Page1">
<f:param name="pageId" value="1" /> </h:commandLink>
<h:commandLink action="#{navigationController.showPage}"
value="Page2">
<f:param name="pageId" value="2" /> </h:commandLink>
<h:commandLink action="#{navigationController.showPage}"
value="Home">
<f:param name="pageId" value="3" /> </h:commandLink>
</h:form>
@ManagedBean(name = "navigationController", eager = true)
@RequestScoped
public class NavigationController implements Serializable {
//this managed property will read value from request parameter
pageId
@ManagedProperty(value="#{param.pageId}")
private String pageId;
//condional navigation based on pageId //if pageId is 1 show
page1.xhtml, //if pageId is 2 show page2.xhtml //else show
home.xhtml
public String showPage(){ if(pageId == null){ return "home"; }
if(pageId.equals("1")){ return "page1"; }else if(pageId.equals("2"))
{ return "page2"; }else{ return "home"; } } }
Resolving Navigation based on from-action
home.xhtml
<h:form>
<h:commandLink action="#{navigationController.processPage1}"
value="Page1" />      
<h:commandLink action="#{navigationController.processPage2}"
value="Page2" />      
</h:form>

@ManagedBean(name = "navigationController", eager = true)


@RequestScoped public class NavigationController implements Serializable {
private static final long serialVersionUID = 1L;
public String processPage1(){ return "page"; }
public String processPage2(){ return "page"; }
}
Resolving Navigation based on from-action
• To resolve views, define following navigation rule in faces-config.xml
<navigation-rule>
<from-view-id>home.xhtml</from-view-id>
<navigation-case>
<from-action>#{navigationController.processPage1}</from-action>
<from-outcome>page</from-outcome>
<to-view-id>page1.jsf</to-view-id>
</navigation-case>
<navigation-case>
<from-action>#{navigationController.processPage2}</from-action>
<from-outcome>page</from-outcome>
<to-view-id>page2.jsf</to-view-id>
</navigation-case>
</navigation-rule>
JSF HTML Tags
Tag Description
<h:commandButton> It is used to create a command button in the JSP page.
We use it to submit the data of a form or to invoke an action.
<h:commandLink> This tag renders an HTML hyperlink, which is capable of
submitting form data and firing some action.
<h:dataTable> This tag is used to create an HtmlDataTable Component and
helps to create a data grid. It automatically populates with data
sets. It renders to an HTML <table> elements but its rows are
automatically created according to the data set stored in the
table.
<h:form> It is used to create an HTML form element on the JSF page.
<h:graphicImage> It is used to display images on a web page.
<h:inputSecret> It renders an HTML <input> element with type set as password.
<h:inputText> It is used to create a single line text box. It renders an HTML
input element of the type "text".
<h:inputTextArea> It is used to create a multiline text input control. It corresponds
to Html rich text box and renders to HTML <textarea> element.
JSF HTML Tags
Tag Description
<h:message> It is used to display a message. The associated UI component
can be referred by setting the for attribute with the id of the
particular component.
<h:messages> This tag is used to display all messages added into FacesContext
at once.
<h:outputFormat> This tag allows a page author to display the concatenated
messages as a message format pattern.
<h:outputLabel> It is used to create the HtmlOutputLabel component on a JSF
page. It is used as a label for a given component.
<h:outputLink> It is used to create an HTML anchor on a web page that helps to
navigate through the current web page to other locations.
<h:outputText> It is used to display single line output string.
<h:panelGrid> It renders to the HTML <table> element. An entire table can be
presented using the <h:panelGrid> tag.
<h:panelGroup> It encapsulates a set of other components to make a single entity.
JSF HTML Tags
Tag Description
<h:selectbooleanChec It is used to create a checkbox component which represents
kbox> single boolean value.
<h:selectManyCheck This tag renders a group of checkboxes to be selected.
box>
<h:selectManyListbo This tag HTML <select> element.
x>
<h:selectManyMenu> It is used to create a multiselect menu.
<h:selectOneListbox It is used a list box. This tag does not allow the selection of more
> than one option from a list box.
<h:selectOneRadio> It is used to display radio buttons.
<h:column> It is used with the <h:dataTable> tag to define the columns
provided in a data grid.
<h:inputText>
<h:inputText value=“SVIT" />
<h:inputText value=“SVIT" readonly=“true”/>
S.N. Attribute & Description

1 Id Identifier for a component


2 Value A component’s value, typically a value binding
3 valueChangeListener A method binding to a method that responds to value changes
4 Converter Converter class name
5 Validator Class name of a validator that’s created and attached to a component
6 Required A boolean; if true, requires a value to be entered in the associated field
7 Accesskey A key, typically combined with a system-defined metakey, that gives focus to an
element
8 Alt Alternative text for nontextual elements such as images or applets
9 Border Pixel value for an element’s border width
10 Dir Direction for text. Valid values are ltr (left to right) and rtl (right to left).
11 Disabled Disabled state of an input element or button
12 Maxlength Maximum number of characters for text fields
13 Readonly Read-only state of an input field; text can be selected in a readonly field but not
edited
14 Width Width of an element
15 Immediate Process validation early in the life cycle
<h:outputText>
The h:outputText tag renders an HTML text.
<h:outputText value="Hello World!" />

Attribute & Description

Id - Identifier for a component


Binding - Reference to the component that can be used in a backing bean

Rendered - A boolean; false suppresses rendering


styleClass - Cascading stylesheet (CSS) class name
Value - A component’s value, typically a value binding
Converter - Converter class name
Style - Inline style information
Title - A title, used for accessibility, that describes an element. Visual browsers
typically create tooltips for the title’s value
<h:commandLink>

<h:commandLink value="Page 1" action="page1" />

<h:commandLink action="#{user.goLoginPage}" value="Login


page" />
<h:graphicImage>

• JSF Tag
<h:graphicImage value="http://www.xyz.com/images/jsf-mini-
logo.png"/>
• Rendered Output
<img src="http://www.xyz.com/images/jsf-mini-logo.png" />
<h:inputSecret>

• JSF Tag
• <h:inputSecret value="password" />
• Rendered Output
• <input type="password" name="j_idt12:j_idt16"
value="password" />
<h:outputFormat> tag
• The h:outputFormat tag renders an HTML text but can
accept parameterised inputs.
• JSF Tag
<h:outputFormat value = "parameter 1 : {0}, parameter 2 :
{1}" >
<f:param value = "Item 1" />
<f:param value = "Item 2" />
</h:outputFormat>
• Rendered Output
parameter 1 : Item 1, parameter 2 : Item 2
<h:commandButton> Attributes
Attribute & Description
Value - A component’s value, typically a value binding
Dir - Direction for text. Valid values are ltr (left to right) and rtl (right to left).
Disabled - Disabled state of an input element or button
Tabindex - Numerical value specifying a tab index
Title - A title, used for accessibility, that describes an element. Visual browsers typically create tooltips for the
title’s value
Width - Width of an element
Onchange - Element’s value changes
Onclick - Mouse button is clicked over the element
Ondblclick - Mouse button is double-clicked over the element
Onfocus - Element receives focus
Onkeydown = Key is pressed
Onkeypress - Key is pressed and subsequently released
Onkeyup - Key is released
Onmousedown - Mouse button is pressed over the element
Onmousemove - Mouse moves over the element
Onmouseout - Mouse leaves the element’s area
Onmouseover -Mouse moves onto an element
Onmouseup - Mouse button is released
<h:commandButton>
<!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">
<body>
<h2>h:commandButton example</h2> <hr />
<h:form>
<h:commandButton value="Click Me!" onclick="alert('Hello World!');" />
<h:commandButton value="checkout”
                     action="#{shoppingCartBean.checkout}" />
</h:form>
</body>
</html>
<h:dataTable>
• h:dataTable tag is used to display data in
tabular fashion.
• Example on next few slides.
Student.java (POJO class)
public class Student {
private String name;
private String department;
private int age;
public Student (String name, String department, int age)
{ this.name = name;
this.department = department;
this.age = age;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDepartment() { return department; }
public void setDepartment(String department) { this.department = department; } public int
getAge() { return age; }
public void setAge(int age) { this.age = age; }
}
UserData.java
import java.io.Serializable; import java.util.ArrayList;
import java.util.Arrays; import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {
private static final long serialVersionUID = 1L;
private String name; private String dept; private int age;
private static final ArrayList<Student> students = new
ArrayList<Student>(Arrays.asList( new Student(“Harsh", “Comp", 18),
new Student(“Rohan", “IT", 17));
public ArrayList<Student> getStudents() { return students; }
public String addStudent(String name,String dept,int age) {
Student student = new Student(name,dept,age);
students.add(student); return null; }
public String deleteStudent(Student student) { students.remove(student); return null; }
}}
home.xhml
<?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>
<h2>DataTable Example</h2>
<h:form>
<h:dataTable value="#{userData.students}" var=“student" >
<h:column>
<f:facet name="header">Name</f:facet> #{student.name}
</h:column>
<h:column>
<f:facet name="header">Department</f:facet> #{student.department}
</h:column>
<h:column>
<f:facet name="header">Age</f:facet> #{student.age}
</h:column>
</h:dataTable> </h:form> </h:body> </html>
h:selectBooleanCheckbox
//JSF...
<h:selectBooleanCheckbox value="#{user.rememberMe}" />
Remember Me

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

//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>
<h:messages>
<h:form>
<h:outputLabel value="Enter Username" />
<h:inputText id="username" size="20" label="UserName" required="true">
<f:validateLength for="username" minimum="5" maximum="20" />
</h:inputText>
<h:outputLabel value="Enter Password" />
<h:inputSecret id="password" size="20" label="Password" required="true"
redisplay="true" >
<f:validateLength for="password" minimum="5" maximum="10" />
</h:inputSecret>
<h:commandButton id="submit" value="Submit" action="result"/>
<h:messages style="color:red;margin:8px;" />
</h:form>
<h:message>
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" />
h:panelGrid
h:panelGrid is a shortcut for making an HTML <table>.
<div align="center">
<h:panelGrid columns="3">
Enter field 1:
<h:inputText ... id="field1"/>
<h:message for="field1" .../>
Enter field 2:
<h:inputText ... id="field2"/>
<h:message for="field2" .../>
...
</h:panelGrid>
<h:commandButton value="Centered Button" .../>
</div>
Attributes for h:panelGrid
align
– The horizontal alignment of the table as a whole (left, right, center). Default is left.
– Text flows around the table for left and right alignments
• border
– The width in pixels of the border around the table (default: 0)
– This is in addition to the border around each cell (the cellspacing).
• bgcolor
– The background color of the table (e.g., "yellow" or "#rrggbb"). Also legal for tr, td, and th.
• background
– The background image for the table. Will be tiled to fit table size. Also legal for td and th (but
not tr).
•width, height
– This specifies the width or height of the table, either in pixels (<table width="250">) or, for
width only, as a percentage of the current browser window width (<table
width="75%">)
• cellspacing
– The space in pixels between adjacent cells. Drawn as a 3D line if border is nonzero, otherwise
empty space in the background color is used
– The default is usually about 3
• cellpadding
– The empty space, in pixels, between the cell’s border and the table element
– The default is usually about 1
<h:panelGrid>
<?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:panelGrid id = "panel" columns = "2" border = "1" cellpadding = "10"
cellspacing = "1">
<f:facet name = "header">
<h:outputText value = "Login"/>
</f:facet>
<h:outputLabel value = "Username" /> <h:inputText /> <h:outputLabel value =
"Password" /> <h:inputSecret />
<f:facet name = "footer">
<h:panelGroup style = "display:block; text-align:center"> <h:commandButton id =
"submit" value = "Submit" /> </h:panelGroup> </f:facet> </h:panelGrid>
<h:outputLink>
• JSF Tag
• <h:outputLink value="page1.jsf" >Page 1</h:outputLink>

• Rendered Output
• <a href="page1.jsf">Page 1</a>
<h:outputLabel>
• The h:outputLabel tag is useful for reading managed bean properties
and displaying their values when the view is rendered. They are
rendered as a label for a corresponding field within the view.
• The h:outputLabel tag is used to attach a label to a specified input
field for the purpose of making it accessible.
• The following page uses an h:outputLabel tag to render the label of a
check box:
<h:selectBooleanCheckbox id="fanClub"
binding="#{cashier.specialOffer}" />
<h:outputLabel for="fanClub" binding="#{cashier.specialOfferText}" >
<h:outputText id="fanClubLabel" value="#{bundle.DukeFanClub}" />
</h:outputLabel>
<h:outputFormat>
In JSF web application, “h:outputFormat” tag is similar with “h:outputText” tag, but
with extra function to render parameterized message.
<?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>
<h:outputFormat>
<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>
<h:outputFormat>
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...
}
<h:selectOneListbox>

• JSF Tag
<h:selectOneListbox value="#{userData.data}">
<f:selectItem itemValue="1" itemLabel="Item 1" />
<f:selectItem itemValue="2" itemLabel="Item 2" />
</h:selectOneListbox>

• Rendered Output
<select name="j_idt6:j_idt8" size="2">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
</select>
<h:selectManyListbox>
• JSF Tag
<h:selectManyListbox value="#{userData.data}">
<f:selectItem itemValue="1" itemLabel="Item 1" />
<f:selectItem itemValue="2" itemLabel="Item 2" />
</h:selectManyListbox>

• Rendered Output
<select name="j_idt6:j_idt8" size="2" multiple="multiple">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
</select>
UserData.java
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {
private static final long serialVersionUID = 1L;
public String[] data = {"1","2","3"};
public String[] getData() { return data; }
public void setData(String[] data) { this.data = data; }
}
home.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">
<head> <title>JSF Tutorial!</title> </head>
<h:body> <h2>h:selectManyCheckbox example</h2> <hr />
<h:form> <h3>Mutiple checkboxes</h3>
<h:selectManyCheckbox value="#{userData.data}">
<f:selectItem itemValue="1" itemLabel="Item 1" />
<f:selectItem itemValue="2" itemLabel="Item 2" />
<f:selectItem itemValue="3" itemLabel="Item 3" />
</h:selectManyCheckbox>
<h:commandButton value="Submit" action="result" />
</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:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:body>
<h2>Result</h2> <hr />
<ui:repeat value="#{userData.data}" var="s">
#{s}
</ui:repeat>
</h:body> </html>
<h:selectOneRadio>
• JSF Tag
<h:selectOneRadio value="#{userData.data}">
<f:selectItem itemValue="1" itemLabel="Item 1" />
<f:selectItem itemValue="2" itemLabel="Item 2" />
</h:selectOneRadio>
• Rendered Output
<table>
<tr> <td><input type="radio" checked="checked" name="j_idt6:j_idt8"
id="j_idt6:j_idt8:0" value="1" />
<label for="j_idt6:j_idt8:0"> Item 1</label></td>
<td><input type="radio" name="j_idt6:j_idt8" id="j_idt6:j_idt8:1"
value="2" />
<label for="j_idt6:j_idt8:1"> Item 2</label></td> </tr> </table>
JSF Core Tags
Tag types Tags
Event Handling tags f:actionlistener
f:valueChangeListener
f:phaseListener
Container for form f:view
tags
Component attributes f:attribute
Configuration tag

Data Conversion tags f:converter


f:convertDateTime
f:convertNumber
Facet tag f:facet
Localization tag f:loadBundle
Parameter f:param
substitution tag
JSF Core Tags
Tag types Tags
Tags for representing f:selectItem
items in a list f:selectItems
Container tag f:subview
Validator tags f:validateDoubleRange
f:validateLength
f:validateLongRange
f:validator
Output tag f:verbatim
JSF components
Component Type Class JSF HTML Tag
Command HtmlCommandButton <h:commandButton>
components HtmlCommandLink <h:commandLink>
Data Component HtmlDataTable <h:DataTable>
Form Component HtmlForm <h:form>
Image Component HtmlGraphicImage <h:graphicImage>
Input Component HtmlInputText <h:inputText>
HtmlInputTextarea <h:inputTextarea>
HtmlInputSecret <h:inputSecret>
Message and HtmlMessage <h:message>
Messsages HtmlMessages <h:messages>
Component
Output Component HtmlOutputFormat <h:outputFormat>
HtmlOutputLabel <h:outputLabel>
HtmlOutputLink <h:outputLink>
HtmlOutputText <h:outputText>
JSF components
Component Type Class JSF HTML Tag
Parameter Does not have Html subclass <f:param>
component
CheckBox HtmlSelectBooleanCheckBox <h:selectBooleanCheckbox>
Component
SelectItem & Do not have Html subclass <f:selectItem>
SelectItems <f:selectItems>
Component
SelectMany / HtmlSelectManyCheckbox
SelectOne HtmlSelectManyListbox
Component HtmlSelectManyMenu
HtmlSelectOneRadio
HtmlSelectOneListbox
HtmlSelectOneMenu
ViewRoot <f:view>
Component
ViewRoot component
• The components in a JSF view are organized in a component tree,
which is headed by javax.faces.component.UIViewRoot component
at root.
• Using UIViewRoot component, you can set and retrieve the current
render kit, Locale for the page, its viewId property.
• We can bypass the navigation system and write your own logic for
navigation by creating a new instance of UIViewRoot, and calling
the setViewRoot() method on the FacesContext object.
JSF Convertor Tags
• JSF provides inbuilt convertors to convert its UI component's
data to object used in a managed bean and vice versa.For
example, these tags can convert a text into date object and can
validate the format of input as well.
• For these tags you need to use the following namespaces of
URI in html node.
• <html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core" >
JSF Convertor Tags
• Following are important Convertor Tags in JSF 2.0:

S.N. Tag & Description

1 f:convertNumber
Converts a String into a Number of desired format

2 f:convertDateTime
Converts a String into a Date of desired format

3 Custom Convertor
Creating a custom convertor
f:convertNumber Tag
• f:convertNumber tag is used to convert a string value to a number of required format.
JSF Tag
• <f:convertNumber minFractionDigits="2" />
S.N. Attribute & Description
1 Type - number (default), currency , or percent
2 Pattern - Formatting pattern, as defined in java.text.DecimalFormat
3 maxFractionDigits - Maximum number of digits in the fractional part
4 minFractionDigits - Minimum number of digits in the fractional part
5 maxIntegerDigits - Maximum number of digits in the integer part
6 minIntegerDigits - Minimum number of digits in the integer part
7 integerOnly - True if only the integer part is parsed (default: false)
8 groupingUsed - True if grouping separators are used (default: true)
9 Locale - Locale whose preferences are to be used for parsing and formatting
10 currencyCode - ISO 4217 currency code to use when converting currency values
11 currencySymbol - Currency symbol to use when converting currency values
f:convertDateTime Tag
• f:convertDateTime tag is used to convert a string value to a date of required format.
It also acts as a validator a required date format.
JSF Tag
• <f:convertDateTime type="date" pattern="dd-mm-yyyy" />

S.N. Attribute & Description

1 type - date (default), time, or both


2 dateStyle - default, short, medium, long, or full
3 timeStyle - default, short, medium, long, or full
4 pattern - Formatting pattern, as defined in java.text.SimpleDateFormat
5 locale - Locale whose preferences are to be used for parsing and formatting
6 timeZone - Time zone to use for parsing and formatting
JSF Validator tags

• JSF Validator Tags


• JSF provides inbuilt validators to validate its UI components.
These tags can validates length of field, type of input which
can be a custom object.
• For these tags you need to use the following namespaces of
URI in html node.
• <html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core" >
JSF Validator tags
• Following are important Validator Tags in JSF 2.0:

S.N. Attribute & Description

1 f:validateLength
Validates length of a string
2 f:validateLongRange
Validates range of numeric value
3 f:validateDoubleRange
Validates range of float value
4 f:validateRegex
Validate JSF component with a given regular expression.
5 Custom Validator
Creating a custom validator
f:validateLength tag
• f:validateLength tag is used to validate length of a string value in a
particular range.
• JSF Tag
• <f:validateLength minimum="5" maximum="8" />

S.N. Attribute & Description

1 Minimum - a String with a minimum number of characters


2 Maximum - a String with a maximum number of characters
f:validateLength Example (UserData.java)
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
public String getName()
{ return name; }
public void setName(String name)
{ this.name = name; }
}
f:validateLength Example (home.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:head> <title>JSF tutorial</title> </h:head>
<h:body>
<h2>h:validateLength Example</h2>
<h:form>
<h:inputText id="nameInput" value="#{userData.name}" label="name" >
<f:validateLength minimum="5" maximum="8" /> </h:inputText>
<h:commandButton value="submit" action="result"/>
<h:message for="nameInput" style="color:red" />
</h:form> </h:body> </html>
f:validateLength Example (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:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:head> <title>JSF Tutorial!</title>
</h:head>
<h:body> <h2>Result</h2> <hr />
Name: #{userData.name}
</h:body>
</html>
f:validateLongRange
• f:validateLongRange tag is used to validate long value in a particular
range.
• JSF Tag
• <f:validateLongRange minimum="5" maximum="200" />

S.N. Attribute & Description


1 Minimum - minimum long value within an optional range
2 Maximum - maximum long value within an optional range
f:validateLongRange (Example)
<?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:head> <title>JSF tutorial</title> </h:head>
<h:body> <h2>h:validateLongRange Example</h2>
<h:form>
<h:inputText id="ageInput" value="#{userData.age}" label="age" >
<f:validateLongRange minimum="5" maximum="200" />
</h:inputText>
<h:commandButton value="submit" action="result"/>
<h:message for="ageInput" style="color:red" />
</h:form> </h:body> </html>
f:validateLongRange (Example – UserData.java)

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable
{
private static final long serialVersionUID = 1L;
private int age;
public double getAge()
{ return age; }
public void setAge(int age)
{ this.age = age; }
}
f:validateDoubleRange
• f:validateDoubleRange tag is used to validate a value to a range of float
values.
JSF Tag
• <f:validateDoubleRange minimum="1000.50" maximum="10000.50" />

S.N. Attribute & Description

1 minimum - minimum double value within an optional range

2 maximum - maximum double value within an optional range


f:validateDoubleRange (Example – home.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:head> <title>JSF tutorial</title> </h:head>
<h:body> <h2>h:validateDoubleRange Example</h2>
<h:form>
<h:inputText id="salaryInput" value="#{userData.salary}" label="salary" >
<f:validateDoubleRange minimum="1000.50" maximum="10000.50" />
</h:inputText>
<h:commandButton value="submit" action="result"/>
<h:message for="salaryInput" style="color:red" />
</h:form> </h:body> </html>
f:validateDoubleRange (Example – UserData.java)

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable
{
private static final long serialVersionUID = 1L;
private double salary;
public double getSalary()
{ return salary; }
public void setSalary(double salary)
{ this.salary = salary; }
}
JSF Custom Validators

• Defining a custom validator in JSF is a three step process

Step Description
No.
1 Create a validator class by implementing
javax.faces.validator.Validator interface.
2 Implement validate() method of above interface.
3 Use Annotation @FacesValidator to assign a unique id to the
custom validator.
Step 1: Create a validator class : UrlValidator.java
package test;
public class UrlValidator implements Validator
{
...
}
Step 2:Implement Validator interface methods :
UrlValidator.java

public class UrlValidator implements Validator


{
@Override
public void validate(FacesContext facesContext, UIComponent
component, String value) throws ValidatorException
{
...
}
}
Step 3: Annotate to register the validator : UrlValidator.java

@FacesValidator("test.UrlValidator")
public class UrlValidator implements Validator
{
@Override
public void validate(FacesContext facesContext, UIComponent
component, String value) throws ValidatorException
{
...
}
}
Use the validator in JSF page

<h:inputText id="urlInput" value="#{userData.data}"


label="URL" >
<f:validator validatorId="test.UrlValidator" />
</h:inputText>
JSF Event handling

• When a user clicks a JSF button or link or changes any value in


text field, JSF UI component fires event which will be handled
by the application code.
• To handle such event, event handler are to be registered in the
application code or managed bean.
• When a UI component checks that a user event has happened, it
creates an instance of the corresponding event class and adds it
to an event list.
• Then, Component fires the event, i.e., checks the list of listeners
for that event and call the event notification method on each
listener or handler.
• JSF also provide system level event handlers which can be used
to do some tasks when application starts or is stopping.
JSF Event handling

S.N. Event Handlers & Description

1 valueChangeListener
Value change events get fired when user make changes in input
components.

2 actionListener
Action events get fired when user clicks on a button or link
component.

3 Application Events
Events firing during JSF lifecycle:
PostConstructApplicationEvent, PreDestroyApplicationEvent ,
PreRenderViewEvent.
JSF valueChangeListener

• When user interacts with input components, such as


h:inputText or h:selectOneMenu, the JSF fires a
valueChangeEvent which can be handled in two ways.

Technique Description
Method Binding Pass the name of the managed bean method
in valueChangeListener attribute of UI
Component.
ValueChangeListener Implement ValueChangeListener interface and
pass the implementation class name to
valueChangeListener attribute of UI Component.
JSF valueChangeListener - Method Binding

• Define a method
public void localeChanged(ValueChangeEvent e){
//assign new value to country
selectedCountry = e.getNewValue().toString(); }

• Use above method


• <h:selectOneMenu value="#{userData.selectedCountry}"
onchange="submit()"
valueChangeListener="#{userData.localeChanged}" >
<f:selectItems value="#{userData.countries}" />
</h:selectOneMenu>
JSF valueChangeListener - ValueChangeListener

• Implement ValueChangeListener
public class LocaleChangeListener implements ValueChangeListener {
@Override
public void processValueChange(ValueChangeEvent event) throws
AbortProcessingException { //access country bean directly
UserData userData = (UserData) FacesContext.getCurrentInstance().
getExternalContext().getSessionMap().get("userData");
userData.setSelectedCountry(event.getNewValue().toString()); } }

• Use listener method


<h:selectOneMenu value="#{userData.selectedCountry}" onchange="submit()">
<f:valueChangeListener type="com.tutorialspoint.test.LocaleChangeListener" />
<f:selectItems value="#{userData.countries}" />
</h:selectOneMenu>
JSF actionListener

• When user interacts with components, such as


h:commandButton or h:link, the JSF fires a action events
which can be handled in two ways.

Technique Description
Method Binding Pass the name of the managed bean method
in actionListener attribute of UI Component.

ActionListener Implement ActionListener interface and pass the


implementation class name to
actionListener attribute of UI Component.
JSF actionListener - Method Binding

• Define a method
• public void updateData(ActionEvent e){ data="Hello
World"; }

• Use above method


• <h:commandButton id="submitButton" value="Submit"
action="#{userData.showResult}"
actionListener="#{userData.updateData}" />
</h:commandButton>
JSF actionListener - ActionListener

• Implement ActionListener
public class UserActionListener implements ActionListener{
@Override
public void processAction(ActionEvent arg0) throws AbortProcessingException
{ //access userData bean directly
UserData userData = (UserData) FacesContext.getCurrentInstance().
getExternalContext().getSessionMap().get("userData");
userData.setData("Hello World"); } }
• Use listener method
<h:commandButton id="submitButton1" value="Submit"
action="#{userData.showResult}" >
<f:actionListener type="UserActionListener" />
</h:commandButton>
UserData.java (Bean Class)
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped;
import javax.faces.event.ValueChangeEvent;
@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {
private static final long serialVersionUID = 1L;
private static Map<String,String> countryMap;
private String data = "sample data";
public String showResult(){ return "result"; }
public void updateData(ActionEvent e){ data="Hello World"; }
public String getData() { return data; }
public void setData(String data) { this.data = data; } }
JSF Phase Event
• This type of event involves the events to be fired in one of the
six phases of JSF lifecycle either during start or towards the
end of each phase.
JSF Phase event example
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
public class CustomPhaseListener implements PhaseListener
{ private static final long serialVersionUID = -
1395570878923714114L;
@Override public void afterPhase(PhaseEvent pe)
{ System.out.println("After phase" + pe.getPhaseId()); }
@Override public void beforePhase(PhaseEvent pe)
{ System.out.println("Before phase" + pe.getPhaseId()); }
@Override public PhaseId getPhaseId()
{ return PhaseId.ANY_PHASE; } }
phaseListener.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:head> <title>Phase Listener example</title> </h:head>
<h:body> <h3>Phase Listener example</h3>
<h:form>
<h:inputText id="mname" />
<h:commandButton id="button" value="Submit" />
<h:messages />
</h:form> </h:body> </html>
Output
• Now run the application and enter some text on phaseListener page and
click the submit button. Check the server logs and following output is
produced.
Before phase RESTORE_VIEW 1
After phase RESTORE_VIEW 1
Before phase APPLY_REQUEST_VALUES 2
After phase APPLY_REQUEST_VALUES 2
Before phase PROCESS_VALIDATIONS 3
After phase PROCESS_VALIDATIONS 3
Before phase UPDATE_MODEL_VALUES 4
After phase UPDATE_MODEL_VALUES 4
Before phase INVOKE_APPLICATION 5
After phase INVOKE_APPLICATION 5
Before phase RENDER_RESPONSE 6
After phase RENDER_RESPONSE 6
JSF Facelet Tags

• JSF provides special tags to create common layout for a web


application called facelets tags.
• These tags gives flexibility to manage common parts of a
multiple pages at one place.
• For these tags you need to use the following namespaces of URI
in html node.
• <html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets" >
JSF Facelet Tags

S.N. Tag & Description

1 Templates
how to use templates using following tags
•<ui:insert>
•<ui:define>
•<ui:include>
•<ui:composition>
2 Parameters
how to pass parameters to a template file using following tag
•<ui:param>
3 Custom
How to create custom tags.

4 Remove
Capability to remove JSF code from generated HTML page.
JSF Facelet Tags – Templates example

S.N. Tag & Description

1 ui:insert
Used in template file. It defines contents to be placed in a
template. ui:define tag can replaced its contents.
2 ui:define
Defines the contents to be inserted in a template.
3 ui:include
Includes contents of one xhtml page into another xhtml page.

4 ui:composition
Loads a template using template attribute. It can also define
a group of components to be inserted in xhtml page.
JSF Facelet Tags –
1. Template Layout (commonLayout.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:ui="http://java.sun.com/jsf/facelets" >
<h:head> <h:outputStylesheet name="common-style.css" library="css" /> </h:head>
<h:body>
<div id="page">
<div id="header">
<ui:insert name="header" >
<ui:include src="/template/common/commonHeader.xhtml" /> </ui:insert> </div>
<div id="content">
<ui:insert name="content" >
<ui:include src="/template/common/commonContent.xhtml" /> </ui:insert> </div>
<div id="footer">
<ui:insert name="footer" >
<ui:include src="/template/common/commonFooter.xhtml" /> </ui:insert> </div>
</div> </h:body> </html>
 commonHeader.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:ui="http://java.sun.com/jsf/facelets" >
<body>
<ui:composition>
<h1>This is default header</h1>
</ui:composition>
</body>
</html>
commonContent.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:ui="http://java.sun.com/jsf/facelets" >
<body>
<ui:composition>
<h1>This is default content</h1>
</ui:composition>
</body> </html>
 commonFooter.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:ui="http://java.sun.com/jsf/facelets" >
<body>
<ui:composition>
<h1>This is default footer</h1>
</ui:composition>
</body> </html>
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:ui="http://java.sun.com/jsf/facelets" >
<h:body>
<ui:composition
template="template/common/commonLayout.xhtml">
</ui:composition>
</h:body> </html>
page1.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:ui="http://java.sun.com/jsf/facelets" >
<h:body>
<ui:composition template="/template/common/commonLayout.xhtml">
<ui:define name="content">
<h2>This is page1 content</h2>
</ui:define>
<ui:define name="footer">
<h2>This is page1 Footer</h2>
</ui:define>
</ui:composition>
</h:body> </html>
PrimeFaces

• PrimeFaces is a lightweight library with one jar, zero-configuration and no


required dependencies. You just need to download PrimeFaces, add the
primefaces-{version}.jar to your classpath and import the namespace to get
started.
• PrimeFaces namespace is necessary to add PrimeFaces components to your pages.
• xmlns:p="http://primefaces.org/ui"  
<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:p="http://primefaces.org/ui">  
      <h:body>  
          <p:spinner />   
    </h:body>  
</html>  
PrimeFaces

• All Tags / Functions


primefaces-p:component() primefaces-p:calendar
primefaces-p:ifAllGranted() primefaces-p:captcha
primefaces-p:ifAnyGranted() primefaces-p:carousel
primefaces-p:ifGranted() primefaces-p:cellEditor
primefaces-p:ifNoneGranted() primefaces-p:clock
primefaces-p:remoteUser() primefaces-p:collector
primefaces-p:userPrincipal() primefaces-p:colorPicker
primefaces-p:widgetVar() primefaces-p:column
primefaces-p:accordionPanel primefaces-p:columnGroup
primefaces-p:ajax primefaces-p:columns
primefaces-p:ajaxStatus primefaces-p:commandButton
primefaces-p:autoComplete primefaces-p:commandLink
primefaces-p:barChart primefaces-p:confirmDialog
primefaces-p:blockUI primefaces-p:contextMenu
primefaces-p:breadCrumb primefaces-p:dashboard
primefaces-p:bubbleChart primefaces-p:dataExporter
primefaces-p:button primefaces-p:dataGrid
primefaces-p:dataTable primefaces-p:dataList
PrimeFaces

• All Tags / Functions


primefaces-p:defaultCommand primefaces-p:lightBox
primefaces-p:dialog primefaces-p:lineChart
primefaces-p:dock primefaces-p:log
primefaces-p:donutChart primefaces-p:media
primefaces-p:draggable primefaces-p:megaMenu
primefaces-p:droppable primefaces-p:menu
primefaces-p:editor primefaces-p:menubar
primefaces-p:effect primefaces-p:menuButton
primefaces-p:feedReader primefaces-p:menuitem
primefaces-p:fieldset primefaces-p:message
primefaces-p:fileDownload primefaces-p:messages
primefaces-p:fileUpload primefaces-p:meterGaugeChart
primefaces-p:focus primefaces-p:mindmap
primefaces-p:galleria primefaces-p:notificationBar
primefaces-p:gmap primefaces-p:ohlcChart
primefaces-p:dialog primefaces-p:orderList
primefaces-p:dock

You might also like