Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (15.81 MB, 597 trang )
Chapter 10 ■ JavaServer Faces
Table 10-1. Main JavaServer Faces Packages
Package
Description
javax.faces
The core JavaServer Faces APIs
javax.faces.application
APIs used to link an application's business logic objects to JavaServer Faces
javax.faces.component
Fundamental APIs for user interface components
javax.faces.context
Classes and interfaces defining per-request state information
javax.faces.convert
Classes and interfaces defining converters
javax.faces.event
Interfaces describing events and event listeners, and concrete event
implementation classes
javax.faces.flow
Classes and runtime API for Faces Flow
javax.faces.lifecycle
Classes and interfaces defining life-cycle management for the JSF implementation
javax.faces.render
Classes and interfaces defining the rendering model
javax.faces.validator
Interface defining the validator model and concrete validator implementation classes
javax.faces.webapp
Classes required for integrating JSF into web applications, including the standard
FacesServlet
Reference Implementation
Mojarra, named after a fish that is found on the South American and Caribbean coasts, is the Oracle open source
reference implementation of JSF 2.2. Mojarra is available in GlassFish v4 and is used in the example presented next.
MyFaces is a project of the Apache Software Foundation which hosts several subprojects related to JavaServer
Faces, including MyFaces Core which is a JSF runtime implementation.
Writing JSF Pages and Components
Writing a JSF page is different from writing an HTML page in the sense that JSF is a back-end technology. If you write a
JSF page and run it straight in a browser, you will not see the graphical representation that you expect. A JSF page needs
to be rendered in HTML on the server before being sent to the browser. A developer can combine JSF components with
core HTML and CSS for styling if she wants, but all this will be rendered by the back end.
A JSF page can be seen as a component tree that uses several tag libraries (the ones defined by the JSF specification
but also in-house or third-party libraries). The page body is compiled into a tree of graphical Java objects and their
values are bound to a backing bean. Therefore, the page has a rich life cycle that handles many different phases.
Anatomy of a JSF Page
A JSF page is basically an XHTML file defining a list of tag libraries on the header and a body containing the graphical
representation. As an example, let’s reuse the page representing a form to create a new book (refer back to Figure 10-1).
Listing 10-7 shows these two fragments. The xmlns:h="http://xmlns.jcp.org/jsf/html" is importing the tag library
called http://xmlns.jcp.org/jsf/html and giving it the alias h. This is then used in the body of the page when we
need to display a specific component that belongs to the tag library (e.g.,
example there is only one tag library that is being used but you can have as many as you need.
321
www.it-ebooks.info
Chapter 10 ■ JavaServer Faces
Listing 10-7. A JSF Page Using a Tag Library and Components
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
xmlns:h="http://xmlns.jcp.org/jsf/html">
Create a new book
Header
The header of a JSF page can be seen as the Java import mechanism: it is where you declare the set of component libraries
that the page will be using. In the following code, an XML prologue is followed by the document type declaration (DTD)
xhtml1-transitional.dtd. The root element of the page is html in the namespace http://www.w3.org/1999/xhtml.
And then a set of XML namespaces declares the tag libraries used in the JSF page with a certain prefix (h and f).
322
www.it-ebooks.info
Chapter 10 ■ JavaServer Faces
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
Table 10-2 lists all the tag libraries that are defined in the JSF and JSTL specifications and that can be used in a
Facelets page. There are the JSF’s core and html graphical components as well as the templating and composite libraries
(allowing you to create custom components). There are also the functions and core libraries that are part of JSTL.
Table 10-2. Tag Libraries Allowed with Facelets PDL
URI
Common Prefix
Description
http://xmlns.jcp.org/jsf/html
h
This tag library contains components and
their HTML renderers (h:commandButton,
h:commandLink, h:inputText, etc.).
http://xmlns.jcp.org/jsf/core
f
This library contains custom actions that
are independent of any particular rendering
(f:selectItem, f:validateLength,
f:convertNumber, etc.).
http://xmlns.jcp.org/jsf/facelets
ui
Tags in this library add templating support.
http://xmlns.jcp.org/jsf/composite
composite
This tag library is used for declaring and defining
composite components.
http://xmlns.jcp.org/jsp/jstl/core
c
Facelets pages can use some of the core JSP tag
libraries (
http://xmlns.jcp.org/jsp/jstl/functions
fn
Facelets pages can use all the function JSP tag libraries.
Body
As shown in Listing 10-7 the body of a JSF page describes a set of well-organized graphical (and nongraphical)
components that ultimately, after being rendered on the server, will give you the HTML representation you want.
A JSF page is a tree of components such as
component is a Java class that extends, directly or indirectly, the abstract javax.faces.component.UIComponent class.
This class defines methods for navigating the component tree, interacting with backing beans, and validating and
converting data as well as the rendering mechanism.
The JSF specification provides a number of built-in HTML and core components you need when building a web
application. All these components extend UIComponent and are listed in Table 10-3. Notice that these classes are all
defined in the javax.faces.component package. Later in the “JSF HTML Components Tags” section you’ll see HTML
components that are in javax.faces.component.html.
323
www.it-ebooks.info
Chapter 10 ■ JavaServer Faces
Table 10-3. Standard JSF UI Components
Component
Description
UIColumn
Represents a column in the parent UIData component
UICommand
Represents graphical components such as buttons, hyperlinks, or menus
UIComponent
Base class for all user interface components in JSF
UIComponentBase
Convenience class that implements the default concrete behavior of all
methods defined by UIComponent
UIData
Supports data binding to a collection of objects; commonly used to render
tables, lists, and trees
UIForm
Represents a user input form and is a container of other components
UIGraphic
Displays an image
UIInput
Represents components to input data such as input fields, text areas, and so on
UIMessage, UIMessages
Responsible for displaying one or several messages for a specific UIComponent
UIOutcomeTarget
Represents graphical buttons and hyperlinks that enable bookmarkability
UIOutput
Represents output components such as labels or any other textual data output
UIPanel
Represents UI components that server as containers for others without
requiring form submission
UIParameter
Represents information that requires no rendering
UISelectBoolean
Represents check boxes
UISelectItem, UISelectItems
Represent a single or multiple items in a selection list
UISelectOne, UISelectMany
Represent components like combo boxes, list boxes, or groups of check boxes
and allow the selection of one or many items
UIViewAction
Represents a method invocation that occurs during the request processing
life cycle
UIViewParameter
Represents a bidirectional binding between a request parameter and a
backing bean property
UIViewRoot
Represents the component tree root and has no graphical rendering
To have an HTML representation of the page described in Listing 10-7, the JSF runtime actually uses the HTML
representation of each component defined in the page. These HTML components inherit from the ones listed in
Table 10-3. For example, a
that extends UIOutput. A
extends UIPanel, and so. The XML in Listing 10-8 is the tree representation of the page described in Listing 10-7.
Listing 10-8. Simplified View of the newBook XML Component Tree
324
www.it-ebooks.info
Chapter 10 ■ JavaServer FacesCreate a new book
■■Tip You can easily get the component tree representation of a JSF page just by adding the
in the page and pressing CTRL+SHIFT+D.
Life Cycle
A JSF page is a component tree with a specific life cycle. You should understand this life cycle so you know when
components are validated or the model is updated. Clicking a button causes a request to be sent from your web
browser to the server. This request is translated into an event that can be processed by your application logic on the
server. All data input by the user enters a phase of validation before the model is updated and any business logic
invoked. JSF is then responsible for making sure that every graphical component (child and parent components) is
properly rendered to the browser. Figure 10-6 shows the different phases of a JSF page life cycle.
325
www.it-ebooks.info
Chapter 10 ■ JavaServer Faces
Figure 10-6. The JSF life cyle
The JSF life cycle is divided into six distinct phases.
1.
Restore view: JSF finds the target view and applies the user’s input to it. If this is the
client’s first visit to the page, JSF creates the view as a UIViewRoot component (root of
the component tree that makes up a particular page as shown in Listing 10-8). If this is
a subsequent request, the previously saved UIViewRoot is retrieved for processing the
current HTTP request.
2.
Apply request values: Values that have come from the request (from input fields in a web
form, from cookies, or from request headers) are applied to the various components of
the page. Note that only UI components update their state—not the backing bean that
composes the model.
3.
Process validations: After the preceding steps, the UI components have a value set. In
the validation processing, JSF traverses the component tree and asks each component to
ensure its submitted value is acceptable. If both conversion and validation are successful
for all components, the life cycle continues to its next phase. Otherwise, the life cycle
goes to the Render response phase with the appropriate validation and conversion error
messages.
4.
Update model values: All the validated component values are bound to the associated
backing beans.
5.
Invoke application: Now you can perform some business logic. Whatever action has been
triggered will be executed on the backing bean, and this is where the navigation comes
into effect, as its return will determine the render response.
6.
Render response: Causes the response to be rendered to the client. The secondary goal of
the phase is to save the state of the view so that it can be restored in the restore view phase
if the user requests it again.
The thread of execution for a request/response cycle can flow through each phase or not, depending on the
request and what happens during the processing; if an error occurs, the flow of execution transfers immediately
to the render response phase. Note that four of these phases can generate messages: apply request values, process
validations, update model values, and invoke application. With or without messages, it is the render response phase
that sends output back to the user.
326
www.it-ebooks.info
Chapter 10 ■ JavaServer Faces
Anatomy of JSF Components
A JSF page is a tree of components. Some of these components have an HTML representation, others don’t and allow
you to validate, convert data, or enable Ajax invocation. You can use several components to design your Web pages.
•
JSF built-in HTML, Core, and Templating components,
•
JSTL tags,
•
Your own homemade components, and
•
Third-party components (open source or commercial).
Sometimes these components need external resources such as images, CSS, or JavaScript. JSF manages these
resources in a very clever way, whereby you can bundle your resources depending on a locale, a library, or a version
number (more on that in the “Resource Management” section). As you will see, JSF pages can also have access to
implicit objects allowing components to use HTTP request parameters, cookie information, or HTTP headers.
JSF HTML Components Tags
JSF’s architecture is designed to be independent of any particular protocol or markup language, and it is also made to
write applications for HTML clients that communicate via HTTP. A user interface for a particular web page is created by
assembling components. Components provide specific functionalities for interacting with an end user (labels, tables,
check boxes, etc.). JSF provides a number of built-in HTML components that cover most of the common requirements.
A page is a tree of components; each component is represented by a class that extends javax.faces.component.
UIComponent and has properties, methods, and events. The components in the tree have parent-child relationships with
other components, starting at the root element of the tree, which is an instance of UIViewRoot (see Listing 10-8). Let’s focus
on using these components on web pages. The javax.faces.component.html package describes HTML components.
Commands
Commands (UICommand) are controls that a user can click to trigger an action. Such components are typically rendered
as a button or a hyperlink. Table 10-4 lists the two command tags that can be used.
Table 10-4. Command Tags
Tag
Class
Description
HtmlCommandButton
Represents an HTML input element for a button of type
submit or reset
HtmlCommandLink
Represents an HTML element for a hyperlink that acts
like a submit button. This component must be placed
inside a form
If on your page you need to add submit buttons, reset buttons, images that can be clicked, or hyperlinks that trigger
an event, do so as follows:
327
www.it-ebooks.info
Chapter 10 ■ JavaServer Faces
By default, a commandButton is of type submit, but it can be changed to type reset (type="reset"). If you want
to turn a button into an image, don’t use the value attribute (that’s the name of the button), instead use the image
attribute to specify the path of the image you want to display. The following is the graphical result of the previous code:
Both buttons and links have an action attribute to invoke a method on a backing bean. For example, to call the
doNew() method of the bookController, use the following EL statement to specify it in the action attribute:
Create a new book
Targets
The previous command components invoke an action on a backing bean by generating an HTTP POST. If you need a
button or a link to go directly to another page by generating an HTTP GET, then you need to use the target components
(UIOutcomeTarget) defined in Table 10-5. Note that these components enable bookmarkability in JSF applications.
Table 10-5. Target Tags
Tag
Class
Description
HtmlOutcomeTargetButton
Renders an HTML input element for a button (produces a
HTTP GET when clicked)
HtmlOutcomeTargetLink
Renders an HTML anchor element (produces a HTTP
GET when clicked)
If your need to navigate from one page to another one without calling a backing bean you can use outcome
components as follows:
328
www.it-ebooks.info
s
The graphical representation is as expected.
Inputs
Inputs (UIInput) are components that display their current value to the user and allow the user to enter different
kinds of textual information. These can be text fields, text areas, or components to enter a password or hidden data.
Table 10-6 lists the input tags.
Table 10-6. Input Tags
Tag
Class
Description
HtmlInputHidden
Represents an HTML input element of type hidden
(which is useful to propagate values outside the
session from page to page)
HtmlInputSecret
Represents an HTML input element of type
password. On a redisplay, any previously entered
value will not be rendered (for security reasons)
unless the redisplay property is set to true
HtmlInputText
Represents an HTML input element of type text
HtmlInputTextarea
Represents an HTML text area element
HtmlInputFile
Allows you to browse a directory and pick up and
upload a file
Many web pages contain forms in which a user has to enter some data or log on using a password. Input
components have several attributes that allow you to change their length, content, or look and feel, as follows:
329
www.it-ebooks.info
Chapter 10 ■ JavaServer Faces
All the components have a value attribute to set their default value. You can use the maxLength attribute to check
that text entered doesn’t go over a certain length or the size attribute to change the default size of the component.
The previous code will have the following graphical representation:
Outputs
Output components (classes that extend UIOutput) display a value, optionally retrieved from a backing bean, a value
expression, or fixed text. The user cannot directly modify the value because it is for display purposes only. Table 10-7
lists the output tags available.
Table 10-7. Output Tags
Tag
Class
Description
HtmlOutputLabel
Renders an HTML