JavaServer Faces Tutorials

Build rich web-based applications with the JavaServer Faces framework


Click here and learn all the new features of JAVA EE 7.

Monday, December 30, 2013


Some web designers or UI programmers use HTML tables to lay out components. In general, creating table markup by hand is a tedious task. In a JavaServer Faces application, you use a panel as a layout container for a set of other components. A panel is rendered as an HTML table. The following table lists the tags used to create panels (the following picture is from the Oracle Java EE 7 online documentation).

  The h:panelGrid is used to represent an entire table. The h:panelGroup tag is used to represent rows in a table. Other tags are used to represent individual cells in the rows.
The columns attribute defines how to group the data in the table and therefore is required if you want your table to have more than one column, like this:

The columns attribute is not mandatory, which means that if you do not specify it, the number of columns defaults to 1. The h:panelGrid tag places components in columns from left to right and top to bottom.

The h:panelGrid tag also has a set of optional attributes that specify CSS classes: columnClasses, footerClass, headerClass, panelClass, and rowClasses. The role attribute can have the value “presentation” to indicate that the purpose of the table is to format the display rather than to show data.

We go back to our Guess_A_Number JSF application (see Lesson 5) and we modify it to include a h:panelGrid tag to represent the entire form.
Here is how the output of our application looks before we add the h:panelGrid tag.


We add the h:panelGrid tag inside the form. Let's define 2 columns.


Let's now change the value of columns to 3


As we have already mentioned, The columns attribute defines how to group the data in the table and therefore is required if you want your table to have more than one column. We also mentioned that the h:panelGrid tag also has a set of optional attributes that specify CSS classes. If the headerClass attribute is specified, the h:panelGrid tag must have a header as its first child. Similarly, if a footerClass attribute value is specified, the h:panelGrid tag must have a footer as its last child.
This is the updated version of the greeting.xhtml


This is the updated version of the CSS file.


You can specify CSS classes for different parts of the table: header, footer, rows, and columns. Because the h:panelGrid tag specifies a headerClass, the h:panelGrid tag must contain a header. The example h:panelGrid tag uses an f:facet tag for the header. Facets can have only one child.


The h:panelGrid is often used with h:panelGroup, which groups two or more components so they are treated as one. For example, you might group an input field and its error message. Let's add the h:panelGroup tag to our application and delete the code for the CSS that refers to the second message. This is the new version of the greeting.xhtml


Michail Kassapoglou

Friday, December 20, 2013


The term Facelets refers to the view declaration language for JavaServer Faces technology. Facelets is a part of the JavaServer Faces specification and also the preferred presentation technology for building JavaServer Faces technology-based applications.
Facelets is a powerful but lightweight page declaration language that is used to build JavaServer Faces views using HTML style templates and to build component trees. Facelets features include the following:
  • Use of XHTML for creating web pages
  • Support for Facelets tag libraries in addition to JavaServer Faces and JSTL tag libraries
  • Support for the Expression Language (EL)
  • Templating for components and pages
Advantages of Facelets for large-scale development projects include the following:
  • Support for code reuse through templating and composite components
  • Functional extensibility of components and other server-side objects through customization
  • Faster compilation time
  • Compile-time EL validation
  • High-performance rendering
Facelets views are usually created as XHTML pages. JavaServer Faces implementations support XHML pages created in conformance with the XHTML Transitional Document Type Definition (DTD), as listed at By convention, web pages built with XTHML have an .xhtml extension.
JavaServer Faces technology supports various tag libraries to add components to a web page. To support the JavaServer Faces tag library mechanism, Facelets uses XML namespace declarions as shown in the following table:


A typical JavaServer Faces web page includes the following elements:
  • A set of namespace declarations that declare the JavaServer Faces tag libraries
  • Optionally, the HTML head (h:head) and body (h:body) tags
  • A form tag (h:form) that represents the user input components

To add the JavaServer Faces components to your web page, you need to provide the page access to the two standard tag libraries: The JavaServer Faces HTML render kit tag library and the JavaServer Faces core tag library. The JavaServer Faces standard HTML tag library defines tags that represent common HTML user interface components. The JavaServer Faces core tag library defines tags that perform core actions and are independent of a particular render kit.
To use any of the JavaServer Faces tags, you need to include appropriate directives at the top of each page specifying the tag libraries.
In this JavaServer Faces tutorial we will analyze the Guess_A_Number JSF application that you can find in Oracle’s online tutorial ( The application presents you with a page that asks you to guess a number from 0 to 10, validates your input against a random number, and responds with another page that informs you whether you guessed the number correctly or incorrectly.


In a typical JavaServer Faces Application, each page of the application connects to a managed bean that serves as a backing bean. The backing bean defines the methods and properties that are associated with the components. In this example, both pages use the same backing bean.


To create a page or view, you add components to the pages, wire the components to backing bean values and properties, and register converters, validators, or listeners on the components.
For our application, XHTML web pages serve as the front end. The first page of the example application is a page called greeting.xhtml. A closer look at various sections of this web page provides more information.


First we declare the content type for the page and then the XML namespace for the tag libraries that is used in the web page.
For Facelets applications, the XML namespace directives uniquely identify the tag library URI and the tag prefix. For example, when you create a Facelets XHTML page, include namespace directives as follows:


The XML namespace URI identifies the tag library location, and the prefix value is used to distinguish the tags belonging to that specific tag library. You can also use other prefixes instead of the standard h or f. However, when including the tag in the page, you must use the prefix that you have chosen for the tag library.
The h:inputText tag accepts user input and sets the value of the managed bean property userNumber through the EL expression #{userNumberBean.userNumber}. The input value is validated for value range by the JavaServer Faces standard validator tag f:validateLongRange. We will discuss validators in another tutorial. We just accept its functionality for now.

The image file,, is added to the page as a resource; so is the style sheet. Web resources are any software artifacts that the web application requires for proper rendering, including images, script files, and any user-created component libraries. Resources must be collected in a standard location, which can be one of the following:

  • A resource packaged in the web application root must be in a subdirectory of a resources directory at the web application root: resources/resource-identifier.
  • A resource packaged in the web application’s classpath must be in a subdirectory of the META-INF/resources directory within a web application: META-INF/resources/resource-identifier. You can use this file structure to package resources in a JAR file bundle in the web application.
Resources can be considered as a library location. Any artifact, such as a composite component or a template that is stored in the resources directory, becomes accessible to the other application components, which can use it to create a resource instance.

An h:commandButton tag with the ID submit starts validation of the input data when a user clicks the button. Using implicit navigation, the tag redirects the client to another page, response.xhtml, which shows the response to your input. The page specifies only response, which by default causes the server to look for response.xhtml.

The tags defined by the JavaServer Faces standard HTML tag library represent HTML form components and other basic HTML elements. These components display data or accept data from the user. This data is collected as a part of a form and is submitted to the server usually when the user clicks a button. 


Most of the component tags support the following attributes:


Michail Kassapoglou

Thursday, December 19, 2013


The lifecycle of a JSF application refers to the various stages of processing of that application, from its initiation to its conclusion. All applications have lifecycle. During a web application lifecycle, common tasks such as the following are performed:

  • Handling incoming requests
  • Decoding parameters
  • Modifying and saving state
  • Rendering web pages to the browser
The JavaServer Faces web application manages lifecycle phases automatically for simple applications or allows you to manage them manually for more complex applications as required. JavaServer Faces applications that use advanced features may require interaction with the lifecycle at certain phases. A clearer understanding of the lifecycle phases is key to creating well-designed components.
Before we continue our analysis on the JavaServer Faces lifecycle, let’s build a new JSF application named Hello2.

The lifecycle of a JavaServer Faces application begins when the client makes an HTTP request for a page and ends when the server responds with the page, translated to HTML.
The lifecycle can be divided into two main phases - execute and render. The execute phase is further divided into sub-phases to support the sophisticated component tree. This structure requires that component data be converted and validated, component events be handled, and component data be propagated to beans in an orderly fashion.

A JavaServer Faces page is represented by a tree of components, called a view. During the lifecycle, the JavAServer Faces implementation must build the view while considering the state saved from a previous submission of the page. When the client requests a page, the JavaServer Faces implementation performs several tasks, such as validating the data input of components in the view and converting input data to types specified on the server side.

The JavaServer Faces implementation performs all these tasks as a series of steps in the JavaServer Faces request-response lifecycle.


**This picture comes from the Oracle online Java EE 7 tutorial**
The request-response lifecycle handles two kinds of requests: initial requests and postbacks. An initial request occurs when a user makes a request for a page for the first time. A postback request occurs when a user submits the form contained on a page that was previously loaded into the browser as a result of executing an initial request.

When the lifecycle handles an initial request, it executes only the Restore View and Render Responses phases, because there is no user input or action to process. Conversely, when the lifecycle handles a postback, it executes all of the phases.

Usually, the first parameter for a JavaServer Faces page comes in from a client, as a result of clicking a link or button component on a JavaServer Faces page. To render a response that is another JavaServer Faces page, the application creates a new view and stores it in the javax.faces.context.FacesContext instance, which represents all of the information associated with processing an incoming request and creating a response. The application then acquires object references needed by the view and calls the FacesContext.renderResponse method, which forces immediate rendering of the view by skipping to the Render Response Phase of the lifecycle.

The JavaServer Faces application lifecyle execute phase contains the following sub-phases:
Restore View Phase
When a request for a JavaServer Faces page is made, usually by an action such as when a link or a button component is clicked, the JavaServer Faces implementation begins the Restore View phase.
During this phase, the JavaServer Faces implementation builds the view of the page, wires event handlers and validators to components in the view, and save the view in the FacesContext instance, which contains all the information needed to process a single request. All the application’s components, event handlers, converters, and validators have access to the FacesContext instance.
If the request for the page is an initial request, the JavaServer Faces implementation creates an empty view during this phase and the lifecycle advances to the Render Response phase, during which the empty view is populated with the components referenced by the tags in the page.
If the request for the page is a postback, a view corresponding to this page already exists in the FacesContext instance. During this phase, the JavaServer Faces implementation restores the view by using the state information saved on the client or the server.

Apply Request Values Phase
After the component tree is restored during a postback request, each component in the tree extracts its new value from the request parameters by using its decode (processDecodes() ) method. The value is then stored locally on each component.
If any decode methods or event listeners have called the renderResponse method on the current FacesContext instance, the JavaServer Faces implementation skips to the Render Response Phase.
If any events have been queued during this phase, the JavaServer Faces implementation broadcasts the events to interested listeners.
At the end of this phase, the components are set to their new values, and messages and events have been queued.

Process Validations Phase
During this phase, the JavaServer Faces implementation processes all validators registered on the components in the tree, by using its validate (processValidators) method. It examines the component attributes that specify the rules for the validation and compares these rules to the local value stored for the component.
If the local value is invalid, or if any conversion fails, the JavaServer Faces implementation adds an error message to the FacesContext instance, and the lifecycle advances directly to the Render Response phase so that the page is rendered again with the error messages displayed. If there were conversion errors from the Apply Request Values phase, the messages for these errors are also displayed.
At this point, if the application needs to be redirect to a different web application resource or generate a response that does not contain any JavaServer Faces component, it can call the FacesContext.responseComplete method.

Update Model Values Phase
After the JavaServer Faces implementation determines that the data is valid, it traverses the component tree and sets the corresponding server-side object properties to the component’s local values. The JavaServer Faces implementation updates only the bean properties pointed at by an input component’s value attribute. If the local data cannot be converted to the types specified by the bean properties, the lifecycle advances directly to the Render Response phase so that the page is re-rendered with errors displayed. This is similar to that happens with validation errors.
At this point, if the application needs to redirect to a different web application resource or generate a response that does not contain any JavaServer Faces components, it can call the FacesContext.responseComplete method.

Invoke Application Phase
During this phase, the JavaServer Faces implementation handles any application-level events, such as submitting a form or linking to another page. Finally, the JavaServer Faces implementation transfers control to the Render Response phase.

Render Response Phase
During this phase, JavaServer Faces builds the view and delegates authority to the appropriate resource for rendering the pages.
If this is an initial request, the components that are presented on the page will be added to the component tree. If this is not an initial request, the components are already added to the three, so they need not be added again.

If the request is a postback and errors were encountered during the Apply Request Values phase, Process Validations phase, or Update Model Values phase, the original page is rendered again during this phase. If the pages contain h:message or h:messages tags, any queued error message are displayed on the page.
After the content of the view is rendered, the state of the response is saved so that subsequent requests can access it. The saved state is available to the Restore View phase.

NOTE: The JavaServer Faces lifecycle spans all of the execute and render processes of an application. It is also possible to process and render only parts of an application, such as a single component. For example, the JavaServer Faces Ajax framework can generate requests containing information on which particular component may be processed and which particular component may be rendered back to the client.

Let’s go back to our simple Hello2 web application and talk about the Cancel button. If you run the application and immediately click on the cancel button you will come across validation errors! This happens because even though you are just clicking the Cancel button with an empty form, it is still handled as a “postback” request. But since the form is empty, validation errors are encountered before the navigation handler can process the “cancel” action event and a response of the same page is rendered back to the client.

The solution is to add an immediate attribute to the Cancel button (or any UICommand component) and its value is set to “true”, it will allow the lifecycle to immediately bypass any validation and navigate back to the index.xhtml page.


In general, setting the immediate attribute to “true” on a UICommand component triggers an action event to be fired immediately during the Apply Request Values phase before the Process Validations phase, so no validation errors are encountered. 
Finally, components that implement the EditableValueHolder interface (like an input field) have the option of having their validations and conversions performed immediately during the Apply Request Values phase or during the usual Process Validations phase, depending on the value of the immediate attribute supplied. More important, having the immediate attribute set to “true” allows the component to be updated with a new validated value before entering the Process Validations phase, where the rest of the validations will occur for non-immediate components. This is useful when performing UI-only modifications, such as enabling an input field to be editable without submitting and validating the entire data in the form.

You will notice the required attribute is set to “true”. If the user attempts to leave the field blank while submitting the form, a built-in validation error message will appear exactly in the same location as the tag.

Michail Kassapoglou


JavaServer Faces from the start was created to adhere precisely to the MVC design pattern. The JSF framework is responsible for interacting with client devices, and it provides tools for tying together the visual presentation, application logic, and business logic of a web application.
The MVC pattern’s purpose is to decouple Model (or data) from the presentation of the data (View). The Controller handles user actions that might result in changes in the model and updates to the views. The scope of JSF is restricted to the presentation layer and its purpose is to connect the view to the model.
An MVC application is segmented into three distinct application components:
  • The Model, which contains the business logic or non-UI code
  • The View, which is all the code necessary to present a UI to the user
  • The Controller, which is a front-end agent that directly handles the user’s requests and dispatches the appropriate view
Let’s see how these three elements are combined to our simple Hello1 application to produce an architecture that yields distinct, separately maintainable code.


JSF connects the view and the model. A view component can be wired to a bean property of a model, such as:

The JSF implementation operates as the controller that reacts to the user by processing action and value change events, routing them to code that updates the model or directs the user to a new page. For example:

When the user clicks the button and the form is submitted to the server, the JSF implementation sets the value of the name property of the hello bean. Then the Faces Controller which is implemented as a servlet responds to the request by preparing an object known as the JSF context, which contains all accessible application data and routes the client to the appropriate View component (page). 
Michail Kassapoglou