7
JavaServer Faces Technology
JavaServer Faces technology is a server-side component framework for building Java
technology-based web applications.
JavaServer Faces technology consists of the following:
= An API for representing components and managing their state; handling events,
server-side validation, and data conversion; defining page navigation; supporting
internationalization and accessibility; and providing extensibility for all these
features,
= Tag libraries for adding components to web pages and for connecting components
to server-side objects
JavaServer Faces technology provides a well-defined programming model and various
tag libraries. The tag libraries contain tag handlers that implement the component
tags. These features significantly ease the burden of building and maintaining web
applications with server-side user interfaces (Us). With minimal effort, you can,
complete the following tasks.
= Create a web page.
= Drop components onto a web page by adding component tags.
= Bind components on a page to server-side data
= Wire component-generated events to server-side application code.
= Save and restore application state beyond the life of server requests.
= Reuse and extend components through customization.
‘This chapter provides an overview of JavaServer Faces technology: After explaining,
what a JavaServer Faces application is and reviewing some of the primary benefits of
using JavaServer Faces technology, this chapter describes the process of creating @
simple JavaServer Faces application. This chapter also introduces the JavaServer Faces
lifecycle by describing the example JavaServer Faces application and its progression
through the lifecycle stages.
‘The following topics are addressed here:
= What Is a JavaServer Faces Application?
= JavaServer Faces Technology Benefits
= A Simple JavaServer Faces Application
= User Interface Component Model
= Navigation Model
= The Lifecycle of a JavaServer Faces Application
JavaServer Faces Technology 7-1What Is a JavaServer Faces Application?
= Partial Processing and Partial Rendering
= Further Information about JavaServer Faces Technology,
7.1 What Is a JavaServer Faces Application?
The functionality provided by a JavaServer Faces application is similar to that of any
other Java web application. A typical JavaServer Faces application includes the
following parts.
+ Asset of web pages in which components are laid out.
= A set of tags to add components to the web page.
= Aset of managed beans, which are lightweight, container-managed objects
(POJOs). In a JavaServer Faces application, managed beans serve as backing beans,
which define properties and functions for UI components on a page.
= Aweb deployment descriptor (web. 201 file).
+ Optionally, one or more application configuration resource files, such as a
faces-config. xa! file, which can be used to define page navigation rules and
configure beans and other custom objects, such as custom components
= Optionally, a set of custom objects, which can include custom components,
validators, converters, or listeners, created by the application developer.
= Optionally, a set of custom tags for representing custom objects on the page.
Figure 7-1 shows the interaction between client and server in a typical JavaServer
Faces application. In response to a client request, a web page is rendered by the web
container that implements JavaServer Faces technology.
Figure 7-1 Responding to a Client Request for a JavaServer Faces Page
|Web Container
rowser mmyfaceletxrint
SS cane
— otter >|
a=
Seam
Te
Renders HTML "
(HTTP Response) myview
The we page nyfaclet. hts is ull using JavaServer Faces component tags
Component tags are used to add components to the view (represented by myView in the
diagram), which is the server-side representation of the page. In addition to
components, the web page can also reference objects, such as the following:
«Any event listeners, validators, and converters that are registered on the
‘components
+ The JavaBeans components that capture the data and process the
application-specific functionality of the components
7-2 Java Platform, Enterprise Edition The Java EE TutorialJavaServer Faces Technology Senefts
‘On request from the client, the view is rendered as a response. Rendering is the
process whereby, based on the server-side view, the web container generates output,
such as HTML or XHTML, that can be read by the client, such as a browser.
7.2 JavaServer Faces Technology Benefits
‘One of the greatest advantages of JavaServer Faces technology is that it offers a clean
separation between behavior and presentation for web applications, A JavaServer
Faces application can map HTTP requests to component-specific event handling and
‘manage components as stateful objects on the server. JavaServer Faces technology
allows you to build web applications that implement the finer-grained separation of
behavior and presentation that is traditionally offered by client-side Ul architectures,
The separation of logic from presentation also allows each member of a web
application development team to focus on a single piece of the development process
and provides a simple programming model to link the pieces. For example, page
authors with no programming expertise can use JavaServer Faces technology tags in a
web page to link to server-side objects without writing any scripts.
Another important goal of JavaServer Faces technology is to leverage familiar
component and web-tier concepts without limiting you to a particular scripting
technology or markup language. JavaServer Faces technology APIs are layered directly
‘on top of the Servlet API, as shown in Figure 7-2.
Figure 7-2 Java Web Application Technologies
JavaServer Faces JavaServer Pages
Standard Tag Library
This layering of APIs enables several important application use cases, such as using
different presentation technologies, creating your own custom components directly
from the component classes, and generating output for various client devices.
Facelets technology, available as part of JavaServer Faces technology, is the preferred
presentation technology for building JavaServer Faces technology-based web
applications. For more information on Facelets technology features, see Chapter 8,
"Introduction to Facelets".
Facelets technology offers several advantages.
= Code can be reused and extended for components through the templating and.
composite component features.
= You can use annotations to automatically register the managed bean as a resource
available for JavaServer Faces applications. In addition, implicit navigation rules
allow developers to quickly configure page navigation (see Navigation Model for
details). These features reduce the manual configuration process for applications.
= Most important, JavaServer Faces technology provides a rich architecture for
‘managing component state, processing component data, validating user input,
and handling events.
JavaServer Faces Technology 7-3{A Simple JavaServer Faces Application
7.3 A Simple JavaServer Faces Application
JavaServer Faces technology provides an easy and user-friendly process for creating
web applications. Developing a simple JavaServer Faces application typically requires
the following tasks, which have already been described in A Web Module That Uses
JavaServer Faces Technology: The hellol Example:
= Creating web pages using component tags
+ Developing managed beans
= Mapping the FacesServiet instance
The hello! example includes a managed bean and two Facelets web pages. When
accessed by a client, the first web page asks the user for his or her name, and the
second page responds by providing a greeting.
For details on Facelets technology, see Chapter 8, "Introduction to Facelets”. For details
on using EL expressions, see Chapter 9, "Expression Language”. For details on the
JavaServer Faces programming model and building web pages using JavaServer Faces
technology, see Chapter 10, "Using JavaServer Faces Technology in Web Pages’
Every web application has a lifecycle. Common tasks, such as handling incoming
requests, decoding parameters, modifying and saving state, and rendering web pages
to the browser, are all performed during a web application lifecycle. Some web
application frameworks hide the details of the lifecycle from you, whereas others
require you to manage them manually.
By default, JavaServer Faces automatically handles most of the lifecycle actions for
you. However, it also exposes the various stages of the request lifecycle so that you can
‘modify or perform different actions if your application requirements warrant it
The lifecycle of a JavaServer Faces application starts and ends with the following
activity: The client makes a request for the web page, and the server responds with the
page. The lifecycle consists of two main phases: Execute and Render.
During the Execute phase, several actions can take place.
+ The application view is built or restored.
+ The request parameter values are applied.
+ Conversions and validations are performed for component values.
+ Managed beans are updated with component values.
+ Application logic is invoked.
For a first (initial) request, only the view is built. For subsequent (postback) requests,
some or all of the other actions can take place.
In the Render phase, the requested view is rendered as a response to the client.
Rendering is typically the process of generating output, such as HTML or XHTML,
that can be read by the client, usually a browser.
The following short description of the example JavaServer Faces application passing.
through its lifecycle summarizes the activity that takes place behind the scenes.
The heliol example application goes through the following stages when itis deployed
on GlassFish Server.
1. When the hel 101 application is built and deployed on GlassFish Server, the
application is in an uninitiated state
7-4 Java Platform, Enterprise Edition The Java EE TutorialUser Interface Component Model
2. When a client makes an initial request for the index. wats web page, the hello1
Facelets application is compiled.
3. The compiled Facelets application is executed, and a new component tree is
constructed for the hel 101 application and placed in a FacesContext.
4, The component tree is populated with the component and the managed bean
property associated with it, represented by the EL expression hel lo. naae,
‘A new view is built, based on the component tree.
The view is rendered to the requesting client as a response,
The component tree is destroyed automatically.
On subsequent (postback) requests, the component tree is rebuilt, and the saved
state is applied.
For full details on the lifecycle, see The Lifecycle of a JavaServer Faces Application,
7.4 User Interface Component Model
In addition to the lifecycle description, an overview of JavaServer Faces architecture
provides better understanding of the technology.
JavaServer Faces components are the building blocks of a JavaServer Faces view. A
‘component can be a user interface (UI) component or a non-UI component.
JavaServer Faces UI components are configurable, reusable elements that compose the
user interfaces of JavaServer Faces applications. A component can be simple, such as a
button, or can be compound, such as a table composed of multiple components.
JavaServer Faces technology provides a rich, flexible component architecture that
includes the following:
= Asset of javax. faces. component ,UIComponent classes for specifying the state and
behavior of Ul components
= Axendering model that defines how to render the components in various ways
= A conversion model that defines how to register data converters onto a component
= Anevent and listener model that defines how to handle component events
= Avvalidation model that defines how to register validators onto a component
This section briefly describes each of these pieces of the component architecture
7.4.1 User Interface Component Classes
JavaServer Faces technology provides a set of Ul component classes and associated
behavioral interfaces that specify all the UI component functionality, such as holding
component state, maintaining a reference to objects, and driving event handling and
rendering for a set of standard components.
‘The component classes are completely extensible, allowing component writers to
create their own custom components. See Chapter 15, "Creating Custom Ul
‘Components and Other Custom Objects” for more information.
The abstract base class for all components is javax. UrComponent.
JavaServer Faces UI component classes extend the UZConponent2ase class (a subclass
of UrConponent), which defines the default state and behavior of a component. The
following set of component classes is included with JavaServer Faces technology.
JavaServer Faces Technology 7-5User Interface Component Model
= ulColumn: Represents a single column of data in a UiData component.
= uTConnand: Represents a control that fires actions when activated.
= utData: Represents a data binding to a collection of data represented by a
vax, faces. model ,Dataodel instance,
= UIFo=n: Represents an input form to be presented to the user. Its child components
represent (among other things) the input fields to be included when the form is
submitted. This component is analogous to the form tag in HTML.
1s ulCraphic: Displays an image,
= UTInput: Takes data input from a user. This class is a subclass of u10utput.
+ ulMessage: Displays a localized error message
+ uINessages: Displays a set of localized error messages.
+ ul0utconerazget: Displays a link in the form of a link or a button.
+ uloueput: Displays data output on a page
+ UlBanel: Manages the layout ofits child components.
+ UIParaneter: Represents substitution parameters
= UlgelectBoolean: Allows a user to set a boolean value on a control by selecting or
deselecting it. This class is a subclass of the ULZaput class,
= UTselectTten: Represents a single item in a set of items.
= Ulselect tens: Represents an entire set of items.
= UTselecttany: Allows a user to select multiple items from a group of items. This
class is a subclass of the UTinput class.
= Ulselectone: Allows a user to select one item from a group of items. This class is a
subclass of the UIIaput class.
= UIvViewParaneter: Represents the query parameters in a request. This class is a
subclass of the UrTapus class.
= ULViewRoot: Represents the root of the component tree.
In addition to extending Uzcomsonent2ase, the component classes also implement one
or more behavioral interfaces, cach of which defines certain behavior for a set of
components whose classes implement the interface.
‘These behavioral interfaces, all defined in the javax. faces. component package unless
otherwise stated, are as follows
+ ActionSource: Indicates that the component can fire an action event. This interface
is intended for use with components based on JavaServer Faces technology 1.1_01
and earlier versions. This interface is deprecated in JavaServer Faces 2.
= ActionSource?: Extends Actonsource and therefore provides the same
functionality. However, it allows components to use the Expression Language (EL)
when they are referencing methods that handle action events.
+ Bditablevalueiolder: Extends Valuetiolder and specifies additional features for
editable components, such as validation and emitting value-change events.
= Naningcon
‘unique ID.
ner: Mandates that each component rooted at this component have a
+ StateHolder: Denotes that a component has state that must be saved between
requests.
7-6 Java Platform, Enterprise Edition The Java EE TutorialUser Interface Component Model
= Valueitolder: Indicates that the component maintains a local value as well as the
option of accessing data in the model tier.
= javax. faces. event .SystenlventiistenerHolder: Maintains a list of
Javax. faces .event .SystensventListener instances for each type of
Javax. faces .event .Systensvent defined by that class.
= javax. faces. component behavior.
attach javax. faces. component .behavior .CL
reusable script.
entBehaviortlolder: Adds the ability to
instances, such as a
UrConmand implements ActionSource? and Statekolder. Uroutpat and component
classes that extend UTOutput implement ScateKolder and ValueKolder. UTTnput and
component classes that extend Urinput implement
StateHolder, and ValueHolder. UzComponentBast
pleValuetiolder,
implements stateKolder.
‘Only component writers will need to use the component classes and behavioral
interfaces directly. Page authors and application developers will use a standard
‘component by including a tag that represents it on a page. Most of the components can
be rendered in different ways on a page. For example, a UiConnand component can be
rendered as a button or a link.
The next section explains how the rendering model works and how page authors can
choose to render the components by selecting the appropriate tags.
7.42 Component Rendering Model
‘The JavaServer Faces component architecture is designed such that the functionality of
the components is defined by the component classes, whereas the component
rendering can be defined by a separate renderer class. This design has several benefits,
including the following
= Component writers can define the behavior of a component once but create
multiple renderers, each of which defines a different way to render the component
to the same client or to different clients.
= Page authors and application developers can change the appearance of a
component on the page by selecting the tag that represents the appropriate
combination of component and renderer.
A render kit defines how component classes map to component tags that are
appropriate for a particular client. The JavaServer Faces implementation includes a
standard HTML render kit for rendering to an HTML client.
‘The render kit defines a set of javax. faces. render. Renderer classes for each
component that it supports, Each Rencierer class defines a different way to render the
particular component to the output defined by the render kit, For example, a
ULSel ectone component has three different renderers. One of them renders the
component as a group of options. Another renders the component as a combo box. The
third one renders the component as alist box. Similarly, a UiConnand component can
be rendered as a bution or a link, using the ib: connandfutton or h: connandLiink tag,
‘The connand part of each tag corresponds to the UIConnand class, specifying the
functionality, which is to fire an action, The Button or Link part of each tag
corresponds to a separate Senderer class that defines how the component appears on
the page.
Each custom tag defined in the standard HTML render kit is composed of the
component functionality (defined in the U7Component class) and the rendering
attributes (defined by the Renderer class)
JavaServer Faces Technology 7-7User Interface Component Model
The section Adding Components to a Page Using HTML Tag Library Tags lists all,
supported component tags and illustrates how to use the tags in an example.
The JavaServer Faces implementation provides a custom tag library for rendering
components in HTML
7.4.3 Conversion Model
A JavaServer Faces application can optionally associate a component with server-side
object data, This object is a JavaBeans component, such as a managed bean. An.
application gets and sets the object data for a component by calling the appropriate
object properties for that component.
When a component is bound to an object, the application has two views of the
component's data,
= The model view, in which data is represented as data types, such as int or long.
= The presentation view, in which data is represented in a manner that can be read
or modified by the user. For example, a java uti’ Date might be represented as a
text string in the format mm/dd/yy or as a set of three text strings.
‘The JavaServer Faces implementation automatically converts component data between
these two views when the bean property associated with the component is of one of
the types supported by the component's data, For example, if a UISelectBoolean
component is associated with a bean property of type java. lang. Boolean, the
JavaServer Faces implementation will automatically convert the component's data
from string to Boolean. In addition, some component data must be bound to
properties of a particular type. For example, a UISelect2oolean component must be
bound to a property of type boolean or java. Lang. Boolean,
Sometimes you might want to convert a component's data to a type other than a
standard type, or you might want to convert the format of the data. To facilitate this,
JavaServer Faces technology allows you to register a javax. faces..convert..Conve:
implementation on Uroutpu components and components whose classes subclass
zOutput. If you register the c implementation on a component, the
Converter implementation converts the component's data between the two views.
You can either use the standard converters supplied with the JavaServer Faces
implementation or create your own custom converter. Custom converter creation is
covered in Chapter 15, "Creating Custom UI Components and Other Custom Objects"
7.4.4 Event and Listener Model
‘The JavaServer Faces event and listener model is similar to the JavaBeans event model
in that ithas strongly typed event classes and listener interfaces that an application can
use to handle events generated by components,
The JavaServer Faces specification defines three types of events: application events,
system events, and data-model events,
Application events are ted to a particular application and are generated by a
trzComponent. They represent the standard events available in previous versions of
JavaServer Faces technology.
An event object identifies the component that generated the event and stores
information about the event. To be notified of an event, an application must provide an
implementation of the listener class and must register it on the component that
generates the event, When the user activates a component, such as by clicking a
7-8 Java Platform, Enterprise Edition The Java EE TutorialUser Interface Component Model
button, an event is fired. This causes the JavaServer Faces implementation to invoke
the listener method that processes the event.
JavaServer Faces supports two kinds of application events: action events and
value-change events.
An action event (class javax. faces event .Actionsvent) occurs when the user
activates a component that implements act ionsource. These components include
buttons and links.
A value-change event (class javax. faces. event .ValueChangeSvent) occurs when the
user changes the value of a component represented by UTIap2t or one of its subclasses.
An example is selecting a check box, an action that results in the component's value
changing to true. The component types that can generate these types of events are the
ULInput, UIselectone, UrSelectMany, and Urselec an components.
Value-change events are fired only if no validation errors are detected,
Depending on the value of the innediate property (see The immediate Attribute) of,
the component emitting the event, action events can be processed during the Invoke
Application phase or the Apply Request Values phase, and value-change events can be
processed during the Process Validations phase or the Apply Request Values phase.
System events are generated by an Object rather than a UzConponent. They are
‘generated during the execution of an application at predefined times. They are
applicable to the entire application rather than to a specific component.
‘A data-model event occurs when a new row of a UIData component is selected.
There are two ways to cause your application to react to action events or value-change
‘events that are emitted by a standard component:
= Implement an event listener class to handle the event, and register the listener on
the component by nesting either an £:valueChangeListener tag or an
E:actionbistener tag inside the component tag
= Implement a method of a managed bean to handle the event, and refer to the
method with a method expression from the appropriate attribute of the
component's tag.
See Implementing an Event Listener for information on how to implement an event
listener, See Registering Listeners on Components for information on how to register
the listener on a component.
See Writing a Method to Handle an Action Event and Writing a Method to Handle a
Value-Change Event for information on how to implement managed bean methods
that handle these events.
See Referencing a Managed Bean Method for information on how to refer to the
‘managed bean method from the component tag
When emitting events from custom components, you must implement the appropriate
‘event class and manually queue the event on the component in addition to
implementing an event listener class or a managed bean method that handles the
event. Handling Events for Custom Components explains how to do this.
745 Validation Model
JavaServer Faces technology supports a mechanism for validating the local data of
editable components (such as text fields). This validation occurs before the
corresponding model data is updated to match the local value.
JavaServer Faces Technology 7-9Navigation Made!
Like the conversion model, the validation model defines a set of standard classes for
performing common data validation checks. The JavaServer Faces core tag library also
defines a set of tags that correspond to the standard
Javax. faces validator. Validator implementations. See Using the Standard
Validators for alist ofall the standard validation classes and corresponding tags,
Most of the tags have a set of attributes for configuring the validator’s properties, such
as the minimum and maximum allowable values for the component's data. The page
author registers the validator on a component by nesting the validator's tag within the
component's tag.
In addition to validators that are registered on the component, you can declare a
default validator that is registered on all ULinput components in the application. For
more information on default validators, see Using Default Validators.
The validation model also allows you to create your own custom validator and
corresponding tag to perform custom validation. The validation model provides two
ways to implement custom validation.
«Implement a valigav!
z interface that performs the validation.
+ Implement a managed bean method that performs the validation.
If you are implementing a Va idator interface, you must also do the following.
+ Register the Validator implementation with the application
= Create a custom tag or use an £:validator tag to register the validator on the
component,
In the previously described standard validation model, the validator is defined for
each input component on a page. The Bean Validation model allows the validator to be
applied to all fields in a page. See Chapter 21, "Introduction to Bean Validation" and
Chapter 22, "Bean Validation: Advanced Topics" for more information on Bean,
Validation.
7.5 Navigation Model
The JavaServer Faces navigation model makes it easy to define page navigation and to
handle any additional processing that is needed to choose the sequence in which pages
are loaded.
In JavaServer Faces technology, navigation is a set of rules for choosing the next page
or view to be displayed after an application action, such as when a button or link is
clicked.
Navigation can be implicit or user-defined. Implicit navigation comes into play when
user-defined navigation rules are not configured in the application configuration
resource files.
When you add a component such as a connandButton to a Facelets page, and assign
another page as the value for its action property, the default navigation handler will
try to match a suitable page within the application implicitly. In the following
example, the default navigation handler will try to locate a page named
response. xhtnil within the application and navigate to it
-chsconendButton value="submit* aetion="response">
User-defined navigation rules are declared in zero or more application configuration
resource files, such as faces-config.xnl, by using a set of XML elements. The default
structure of a navigation rule is as follows:
7-10. Java Platform, Enterprise Edition The Java EE TutorialNavigation Model
‘
enavigation-case>
User-defined navigation is handled as follows.
1s Define the rules in the application configuration resource file.
= Refer to an outcome string from the button or link component's action attribute
This outcome string is used by the JavaServer Faces implementation to select the
navigation rule.
Here is an example navigation rule:
froneview-ic> gre
1g -zhtml
successe/ fron-outcone>
a> response. xbtnl
Higation-case>
This rule states that when a command component (such as an h:cornandButton or an
hiconnandiink) on greeting..xhtal is activated, the application will navigate from the
greet ing. xhtml page to the response. xhtml page if the outcome referenced by the
button component's tag is success. Here is an h:conmandBut con tag from
greet ing. xhtml that would specify a logical outcome of success:
Adetzubmit® value="Submit™ a
‘As the example demonstrates, each navigation-rule element defines how to get from
‘one page (specified in the fxom-view-id element) to the other pages of the application.
The nayiigation-rule elements can contain any number of navigation-case elements,
‘each of which defines the page to open next (defined by to-view- id) based on a
logical outcome (defined by fzon-outcoze)
In more complicated applications, the logical outcome can also come from the return,
value of an action method in a managed bean. This method performs some processing
to determine the outcome. For example, the method can check whether the password
the user entered on the page matches the one on file. Ifit does, the method might
return success; otherwise, it might return failure. An outcome of fai lure might
result in the logon page being reloaded. An outcome of success might cause the page
displaying the user's credit card activity to open. If you want the outcome to be
returned by a method on a bean, you must refer to the method using a method.
expression with the act ion attribute, as shown by this example:
When the user clicks the button represented by this tag, the corresponding component
‘generates an action event. This event is handled by the default
Javax. faces event ActionListener instance, which calls the action method
referenced by the component that triggered the event. The action method returns a
logical outcome to the action listener.
JavaServer Faces Technology 7-11Navigation Made!
The listener passes the logical outcome and a reference to the action method that
produced the outcome to the default javax. faces. application. Navigationiandl)
vfandlex selects the page to display next by matching the outcome or
the action method reference against the navigation rules in the application
configuration resource file by the following process.
1. The Navigat iontand:
currently displayed.
selects the navigation rule that matches the page
2, Itmatches the outcome or the action method reference that it received from the
default javax. faces event .Actionbistener with those defined by the navigation
3. It tries to match both the method reference and the outcome against the same
navigation case.
4, If the previous step fails, the navigation handler attempts to match the outcome.
5. Finally, the navigation handler attempts to match the action method reference if
the previous two attempts failed.
6, _Ifno navigation case is matched, it displays the same view again.
When the Navigationtandler achieves a match, the Render Response phase begins.
During this phase, the page selected by the Navigat ionkandl er will be rendered.
The Duke's Tutoring case study example application uses navigation rules in the
business methods that handle creating, editing, and deleting the users of the
application. For example, the form for creating a student has the following
h:commandduttoa tag:
hsconmandbutton id=" submit
action=*#(adnindean creates:
es
e| ‘action. eubmit'))*/>
-udent¥anager nexstudent!
value="#()
The action event calls the dukestutoring. ejb. AdninBean. createStudent method:
public String createstudent (Stu:
fen. persist (s
>
The return value of createdstudent has a corresponding navigation case in the
faces-con‘ig. xsl configuration file:
le
navigation
Eron-view-id> /adain/atudent /createstulent.xatml
ex-id> /adnin/index.xheml<
Imavigatien-case>
Render Response } Complete
Update Model Values
ee
Conversion Erars/-| Process Events — Response —>
Render Response + Complete
Invoke Application
¥
Process Events Response >
Complete
1 PI
Render Response >
ee
Faces Response
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 Response 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 request 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 .PacesContext 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
sponse method, which forces immediate rendering of the
view by skipping to the Render Response Phase of the lifecycle, as is shown by the
arrows labelled Render Response in Figure 7-3.
the FacesContext
‘Sometimes, an application might need to redirect to a different web application
resource, such as a web service, or generate a response that does not contain
JavaServer Faces components. In these situations, the developer must skip the Render
Response phase by calling the PacesContex: ,responseCompieve method. This
situation is also shown in Figure 7-3, with the arrows labelled Response Complete.
The most common situation is that a JavaServer Faces component submits a request
for another JavaServer Faces page. In this case, the JavaServer Faces implementation
7-14 Java Platform, Enterprise Edition The Java EE TutorialThe Lifecycle of a JavaServer Faces Application
handles the request and automatically goes through the phases in the lifecycle to
perform any necessary conversions, validations, and model updates and to generate
the response.
There is one exception to the lifecycle described in this section. When a component's
nnediate attribute is set to true, the validation, conversion, and events associated
with these components are processed during the Apply Request Values Phase rather
than in a later phase.
‘The details of the lifecycle explained in the following sections are primarily intended.
for developers who need to know information such as when validations, conversions,
and events are usually handled and ways to change how and when they are handled.
For more information on each of the lifecycle phases, download the latest JavaServer
Faces Specification documentation from http: //jep.ozg/en/jsz/detail2id=344,
The JavaServer Faces application lifecycle Execute phase contains the following
subphases:
= Restore View Phase
= Apply Request Values Phase
Process Validations Phase
= Update Model Values Phase
= Invoke Application Phase
= Render Response Phase
7.6.2 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 saves 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 isa postback, a view corresponding to this page already
‘exists in the FacesContex: instance. During this phase, the JavaServer Faces
implementation restores the view by using the state information saved on the client or
the server.
7.6.3 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,
any decode methods or event listeners have called the rendereaponse method on
the current FacesContext instance, the JavaServer Faces implementation skips to the
Render Response phase.
JavaServer Faces Technology 7-15The Lifecycle of a JavaServer Faces Application
If any events have been queued during this phase, the JavaServer Faces
implementation broadcasts the events to interested listeners.
If some components on the page have their innediate attributes (see The immediate
Attribute) set to true, then the validations, conversions, and events associated with
these components will be processed during this phase. If any conversion fails, an error
message associated with the component is generated and queued on FacesContext.
This message will be displayed during the Render Response phase, along with any
validation errors resulting from the Process Validations phase.
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 ZacesContext .responseComplete method,
At the end of this phase, the components are set to their new values, and messages and
events have been queued.
Ifthe current request is identified as a partial request, the partial context is retrieved
from the FacesContext, and the partial processing method is applied.
7.6.4 Process Validations Phase
During this phase, the JavaServer Faces implementation processes all validators
registered on the components in the tree by using its validate (processVal idators)
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. The JavaServer
Faces implementation also completes conversions for input components that do not
have the innediate attribute set to true.
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.
If any val igate methods or event listeners have called the renderResporse method on
the current FacesContext, the JavaServer Faces implementation skips to the Render
Response phase.
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 Zacescontext .responseComplete method,
Ifevents have been queued during this phase, the JavaServer Faces implementation
broadcasts them to interested listeners.
If the current request is identified as a partial request, the partial context is retrieved
from the FacesContext, and the partial processing method is applied,
7.6.5 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 components local values. The JavaServer Faces implementation updates only
the bean properties pointed at by an input component's value attribute. Ifthe 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. Ths i similar to what happens with validation errors
7-16 Java Platform, Enterprise Edition The Java EE TutorialPartial Processing and Partial Rendering
If any updatexodels methods or any listeners have called the renderResponse method
on the current FacesContext instance, the JavaServer Faces implementation skips to
the Render Response phase.
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 .responseConplete method,
If any events have been queued during this phase, the JavaServer Faces
implementation broadcasts them to interested listeners,
If the current request is identified as a partial request, the partial context is retrieved
from the FacesContext, and the partial processing method is applied.
7.6.6 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.
Atthis point, ifthe 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..responseConplete method.
If the view being processed was reconstructed from state information from a previous
request and if a component has fired an event, these events are broadcast to interested.
listeners,
Finally, the JavaServer Faces implementation transfers control to the Render Response
phase.
7.6.7 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 represented on the page will be
added to the component tree. If this is not an initial request, the components are
already added to the tree and 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. Ifthe pages contain h-message or
Ihrnessages tags, any queued error messages 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.
7.7 Partial Processing and Partial Rendering
The JavaServer Faces lifecycle spans all of the execute and render processes of an
application. Iti also possible to process and render only parts of an application, such
asa 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.
‘Once such a partial request enters the JavaServer Faces lifecycle, the information is
identified and processed by a javax. faces context. PartialViewontext object. The
JavaServer Faces lifecycle is still aware of such Ajax requests and modifies the
component tree accordingly.
JavaServer Faces Technology 7-17Further information about JavaServer Faces Technology
The execute and render attributes of the £:ajax tag are used to identify which
components may be executed and rendered. For more information on these attributes,
see Chapter 13, "Using Ajax with JavaServer Faces Technology",
7.8 Further Information about JavaServer Faces Technology
For more information on JavaServer Faces technology, see
+ JavaServer Faces 2.2 specification
beep: //Jep.org/en/jsr/detail?ide344
= JavaServer Faces project website:
beeps: //Javaserverfaces. java.net/
7-18 Java Platform, Enterprise Edition The Java EE Tutorial