javaserver faces (jsf) basicsgeneticmail.com/.../jsf/jsfbasics_speakernoted.pdf · (jsf) basics ok,...
TRANSCRIPT
1
1
JavaServer Faces(JSF) Basics
OK, this session is about JSF basics. As some of you probably know, JSF is an extremely important Java technology going forward.
04/29/2004
2
2
Sang Shin
[email protected]/j2eeadvanced
Java™ Technology EvangelistSun Microsystems, Inc.
04/29/2004
3
3
Disclaimer & Acknowledgments? Even though Sang Shin is a full-time employee of Sun
Microsystems, the content in this presentation is created as his own personal endeavor, and thus does not reflect any official stance of Sun Microsystems.
? Sun Microsystems is not responsible for any inaccuracies in the contents.
? Acknowledgments: – I borrowed some presentation slides from the following sources
? “Web application frameworks” codecamp material authored by Doris Chen of Sun Microsystems
– Many slides and speaker notes are created from JSF tutorial
04/29/2004
4
4
Revision History? 12/15/2003: version 1: created by Sang Shin ? 04/03/2004: version 2: sample code is from JSF 1.0,
speaker notes are edited ? Things to do
– slides need to be polished– speaker notes needed to be edited and polished
04/29/2004
5
5
Topics ? What is and why JSF?? Quick overview on JSF architecture, concepts,
and features? Developer roles (in Web app development)? Request processing life cycle? UI Component model? Using JSF tag libraries
– Core tags, HTML tags? Backing beans (model beans)? Page navigation
These are the topics we will talk about in this presentation. The goal of this presentation is to go over the basic features of JSF so that you get some clear sense on how to build and deploy a basic JSF application.
04/29/2004
6
6
Advanced Topics (We will talk about these in Advanced JSF Session)
? Backing bean (model objects) management? Navigations? Event and listeners? Validation? Rendering? Conversion? Internationalization and Localization? Custom UI component
In the advanced JSF and custom UI component presentations, we will cover the topics mentioned in this slide in-depth.
04/29/2004
7
7
HistoricalBackground
Let's talk about historical background first by looking at the evolution of Web application technologies.
04/29/2004
8
8
Background? Web applications are a very popular entry
point for Java™ 2 Platform, Enterprise Edition (J2EE™) developers
? Powerful foundational technologies- Servlets- JavaServer ™ Pages (JSP™)- Portlets
? Diverse toolkits- Custom tag libraries- Development tools- Application frameworks
Web application programming has been a very popular entry to J2EE programming for many developers. That is, before they make use of advanced features of J2EE such as EJB, developers typically write web applications first.
And as we all know, the foundation web-tier technologies such as Servlet, JSP, and recently Portlet provide powerful and yet flexible architecture.
Web applications can also leverage diverse set of toolkits such as custom tag libraries, development tools and popular application frameworks such as Struts, which certainly gave developers enough incentive to look into Java based Web technology.
04/29/2004
9
9
Background
? Building high-quality web application user interfaces is hard- HTTP request/response model- HTML dialect(s) and browser capabilities- Need to support multiple client device types
? Opportunity to attract a new developer community to the Java Platform- Corporate Developers- IT Developers
Now as developers write more sophisticated Web applications, they have found that, unlike in the case of building standalone Swing based application, building high-quality web application UI interface is very hard. There are several reasons for this. First there is only a simple request/response model in HTTP. There are also several dialects in HTML language itself and browsers. And the fact that there are several client types to be supported also make things complicated.
Java technology and platform is known to provide extremely powerful and flexible means for writing sophisticated enterprise programs yet it is not known for providing “easy to develop” kind of environment. And Corporate developers are folks who do prefer building applications with minimum amount of time with minimum learning curve. And the need to court these corporate developers is getting bigger and bigger and J2EE is establishing itself as “the” platform of choice of writing any kind of application in corporate environment.
So these are fertile ground for standard UI framework, thus the advent of JavaServer Faces (JSF).
04/29/2004
10
10
What is & Why JSF?
So let's talk about what is and why JSF first.
04/29/2004
11
In short, JSF is a server side user interface component framework for Java technology based Web applications.
Please note that it is server side instead of client side framework. What this means is that, in JSF architecture, many things that are related to UI management are handled at the server instead of at client side. Of course, the prime example of client side UI framework is Swing.
Please also note that JSF is a UI component framework. What this means is, under JSF architecture, UI is handled by a set of UI components as we will learn later on. The concept of UI component is very important in understanding JSF.
11
JavaServer™ Faces (JSF) Framework Is…
A server side user interface component framework for Java™ technology-based web applications
04/29/2004
12
In a bit more technical definition, JSF is a specification and reference implementation for Web application development framework. And the specification defines various things such as UI component model, event and listener model, validator model, back-end data integration model.
The goal of JSF is to allow tool vendors to provide easy to use tools leveraging JSF underneath so that developers can build Web applications using, for example, drag and drop model as they do in standalone Swing based applications. And a good example of the tool that leverages JSF underneath is Sun Java Studio Creator.
12
What is JSF?? A specification and reference
implementation for a web application development framework
– Components– Events– Validators– Back-end-data integration
? Designed to be leveraged by tools– Sun Java Studio Creator
04/29/2004
13
Now let's talk about value propositions of JSF. You can consider JSF provides the MVC based Web application framework. Again it provides clean separation of roles as we will talk about later in this presentation. JSF is easy to use. And it provides UI component framework which is extensible. It also provides rendering architecture in which UI components can be associated with multiple renderers. JSF is also designed with multiple client types in mind.
13
Why JSF? (page 1)
? MVC for web applications? Clean separation of roles? Easy to use? Extensible Component and Rendering
architecture? Support for client device independence? Standard? Huge vendor and industry support
04/29/2004
14
One of the greatest advantages of JavaServer Faces technology is that it offers a clean separation between behavior and presentation. Web applications built with JSP technology partially achieve this separation. However, a JSP application cannot map HTTP requests to component-specific event handling or manage UI elements as stateful objects on the server. JavaServer Faces technology allows you to build Web applications that implement finer-grained separation of behavior and presentation traditionally offered by client-side UI architectures.
The separation of logic from presentation also allows each member of a Web application development team to focus on their piece of the development process, and provides a simple programming model to link the pieces together. For example, Page Authors with no programming expertise can use UI component tags to link to application code from within a Web page without writing any scripts.
Another important goal of JavaServer Faces technology is to leverage familiar UI-component and Web-tier concepts without limiting you to a particular scripting technology or markup language. While JavaServer Faces technology includes a JSP custom tag library for representing components on a JSP page, the JavaServer Faces technology APIs are layered directly on top of the Servlet API. This layering of APIs enables several important application use-cases such as: using another presentation technology besides JSP pages, creating your own custom components directly from the component classes, and generating output for different client devices.
Most importantly, JavaServer Faces technology provides a rich architecture for managing component state, processing component data, validating user input, and handling events.
14
Why JSF? (page 2)
? Offers finer-grained separation of behavior and presentation than JSP
– Component-specific event handling – UI elements as stateful objects on the server
? UI-component and Web-tier concepts without limiting you to a particular scripting technology or markup language
– Can work with any presentation technology including JSP
04/29/2004
15
So in summary, why do we need JSF when we have Servlet and JSP? Furthermore, why do we need JSF when we have a popular web application frameworks such as Struts?
As was mentioned in previous slide, JSP and Servlet do not provide built-in UI component model.
What about Struts? Struts is designed with a different focus. The focus of Struts is to provide a controller framework while the focus of JSF is to provide UI component framework. So Struts does not provide the built-in UI component model. And because of that, it does not support UI component event model, nor state management of UI components, and because Struts is more or less tied up with HTML, it does not support the independence between UI components and a particular renderer.
15
Why JSF? (page 3)
? JSP and Servlet– No built-in UI component model
? Struts (I am not saying you should not use Struts)– No built-in UI component model– No built-in event model for UI components– No built-in state management for UI components– No built-in support of multiple renderers (Struts is
more or less tied up with HTML)– Not a standard (despite its popularity)
? Struts and JSF can be used together
04/29/2004
16
16
JSF is a UI Framework for Java Web Applications
Client
Server
UI request
Response
(events)
(markup)
As I mentioned, JSF provides User interface framework, which runs on the service side.
Let's say a client makes a request. The request goes across the network to the server, where JSF framework builds up UI representation and renders back to the client in whatever mark up language that is appropriate to the client.
The user interacts with that page, and submit a request to the server for processing. The JSF framework then interprets the request parameters, and decode them and converts them into events and dispatch them to event handling logic.
04/29/2004
17
17
JSF Design Goals
04/29/2004
18
18
JavaServer Faces Must Be ...? Tool friendly? Client device / protocol neutral? Usable with JavaServer Pages (JSP)? Usable without JSP? Useful in the context of HTML and today's
browsers? Scalable
When JSF expert group started working on JSF specification, they had a few things in mind.
First, JSF should be tool friendly. If you think about how developers are building Swing application, they don't write their apps directly using Swing APIs. Instead, they would use an IDE in which they can do drag and dropping UI widgets. And the JSF expert group expect the same thing for building Web applications. They expect tool vendors will provide a way in which developers can drag and drop UI widgets for building Web applications.
The next goal is to make JSF to be client device and protocol neutral. That is, there has to be a clean separation between UI component model and how UI components are rendered to a particular client using a particular protocol. Of course, HTML browser using HTTP protocol is the most pervasive form of client device and protocol and they should be well supported. But the point is the UI component model should be able to accommodate other client types and protocols easily as they come.
Given that JSP is the most popular presentation technology, JSF should be able to work well with JSP but JSF should also work well with other presentation technologies.
04/29/2004
19
Other requirements include the architecture of JSF should follow MVC design pattern. And as was discussed before, it should provide UI component model in which state and event model are supported. By the way, by “state”, we are talking about state of the UI component not the “session state”. And the input validation and error handling should be supported.
19
Our Requirements? MVC? UI components? State management? Events? Validation and error handling? Lightning fast performance
04/29/2004
20
20
How the JSF Specification Fits In
JSF App
Servlets (2.3)
JSP (1.2) JSF API
JSF Tags
JSF App
This picture shows where JSF fits in with other Web-tier technologies. First of all, just like all the other Web-tier technologies, JSF is built over Servlet. In fact, most of JSF APIs are built over Servlet directly. JSF also leverages JSP as well. And JSF custom tags which we will talk about in detail later on are based on JSP custom tag technology.
04/29/2004
21
21
Quick Overview on JSF Architecture,
Concept, & Features
Now I would like to spend the next 10 or so minutes giving you a quick overview of JSF architecture, concept, and features. Again we will go over these in detail later on. But given that all the features of JSF are somewhat interrelated, it is good to know the big picture first.
04/29/2004
22
22
JSF Architecture
HTML RenderKit
AppBackend
DesktopBrowser
Phone
Frontctrl
JSF Page
JSF Page
WML
HTML
Server
WML RenderKit
This picture shows JSF architecture in a somewhat simplified manner.
Just like any other MVC-based architecture, JSF architecture has its own Front controller called FacesServlet. The role of this controller is basically a gatekeeper.
As we will learn later on, a JSF page is made of a tree of UI components. These UI components can be associated with backend model objects called backing beans. These backing beans handle application logic (or sometimes called business logic) handling.
When a page has to be rendered to a particular client type, whether the client type is a HTML browser running on a desktop or WML browser running on a wireless phone, a particular renderer is used for displaying the data maintained in the UI components. In other words, a same UI component is used for displaying information on different client types using different protocols.
04/29/2004
23
23
Important Basic Capabilities
? Extensible UI component model? Flexible rendering model? Event handling model? Validation framework? Basic page navigation support? Internationalization? Accessibility
So just to repeat the important JSF features and capabilities here one more time, JSF UI component model is extensible. That is, you as a developer can use the built-in UI components that come with a typical JSF implementation or you can extend them. JSF also provides flexible rendering model as was mentioned. That is, UI components in JSF are not tied with a particular rendering technology such as HTML. This means any rendering technology can be used for displaying information maintained in the UI components.
JSF also supports event handling model. For example, when you click on a UI component on a JSF page, it will generate an event and any server side programs which registered to receive event notifications will be notified.
JSF also supports page navigation through a configuration file. In this sense, this is quite similar with Struts.
JSF also supports internationalization and accessibility.
04/29/2004
24
24
Key JSF Concepts
? UIComponent – Render-independent characteristics– Base class with standard behaviors
? Standard UIComponent Subclasses:– UICommand, UIForm, UIGraphic, UIInput,
UIOutput, UIPanel, UISelectBoolean, UISelectMany, UISelectOne
? FacesEvent – Base class for request and application events
? Validator – Base class for standard and application defined validators
So let's go over some of the key JSF concepts. Again, we talked about these concepts already a bit.
First, the concept of UI component is extremely important for you to understand. I would say that if you understand the concept of UI component, you understand 90% of JSF architecture.
04/29/2004
25
25
Key JSF Concepts? Converter – Plug-in for String-Object
conversion? FacesContext – Per-Request State:
– Servlet request, response, session– JSF request, response trees– Model reference expression evaluators
? Syntax similar to the expression language of the JSP Standard Tag Library (JSTL) 1.0
? Primary interface between components and the data provided by (or to) the application
04/29/2004
26
26
Key JSF Concepts? Renderer – Converts components to and
from a specific markup language– Supports render-dependent attributes on
components– May support more than one component type
? RenderKit – Library of Renderers– Extensible at runtime– Basic HTML RenderKit is part of the specification
04/29/2004
27
27
Relationship to Other JSRs? JSF is based on:
– Servlet 2.3 (JSR-53)– JSP 1.2 (JSR-53)
? JSF must be synergistic with:– JSTL 1.0 (JSR-52)– Portals (JSR-168)
? JSF is not part of J2EE 1.4 standard yet– Will be considered for J2EE 1.5– It is included in J2EE 1.4 SDK, however
04/29/2004
28
28
Developer Roles
04/29/2004
29
29
JSF Developer Roles
Page Author
Application Developer
ComponentDeveloper
Tools Developer
JSF Implementor/
Extender
Application Extensions
Because of the division of labor enabled by the JavaServer Faces technology design, JavaServer Faces application development and maintenance can proceed quickly and easily.
The members of a typical development team are those mentioned in the picture above. In many teams, individual developers play more than one of these roles, however, it is still useful to consider JavaServer Faces technology from a variety of perspectives based on primary responsibility.
So let's talk about each of these roles in the following slides.
04/29/2004
30
Page Authors, who use a markup language, like HTML, author pages for Web applications. When using the JavaServer Faces technology framework, page authors will most likely use the tag library exclusively. They play the role of assembler of prebuilt custom tags typically by using “drop and drop” IDE like Sun Java Studio Creator. A typical custom tags is, as we will see later on, in the form of combination of a UI component and a renderer.
Component Writers, who have user-interface programming experience and prefer to create custom components using Java programming language. These people can create their own components directly from the component classes, or they can extend the standard components provided by JavaServer Faces technology. They might also create renderers for a particular client type. JSF implementation comes with HTML renderers.
30
Roles Definition? Page Author – Creates the user interface
of a web application– Familiar with markup language(s) to be used– Assembler of prebuilt components– Uses “Drag and drop” IDE like Sun Java Studio
Creator? Component Writer – Creates reusable
components, renderers, and libraries– Components – Render-independent properties– Renderers – Render-dependent properties
04/29/2004
31
Application Developers are people who program the server side objects called backing beans or model objects, the event handlers, the validators, and the page navigation.
Application developers can also provide the extra helper classes.
31
Roles Definition? Application Developer – Creates the
server-side functionality of a web application not directly related to the user interface
– Business logic components implemented in standard J2EE ways (EJBs, JavaBeans, Connectors)
– Persistence tier components implemented in standard J2EE ways (EJBs, JDBC, Connectors)
– Model data exposed to user interface via JavaBean programming model
– Validator, Convertor, Event handler
04/29/2004
32
Tools Vendors provide tools that leverage JavaServer Faces technology to make building server-side user interfaces even easier.
32
Roles Definition? Tool Provider – Creates tools to assist page
authors, component writers, and application developers
– GUI-oriented page development tools– IDEs to facilitate creation of components– Application generators (from high level description)– Web application frameworks that utilize JSF
components for their user interface– Example: Sun Java Studio Creator
? JSF Implementor – Provides runtime environment to execute JSF webapps
– J2EE SDK 1.4
04/29/2004
33
33
Request ProcessingLife Cycle
Most users of JavaServer Faces technology won't need to concern themselves with the request processing life-cycle. However, knowing that JavaServer Faces technology properly performs the processing of a page, a developer of JavaServer Faces applications doesn't need to worry about rendering problems associated with other UI framework technologies.
One example involves state changes on individual components. If the selection of a component such as a checkbox effects the appearance of another component on the page, JavaServer Faces technology will handle this event properly and will not allow the page to be rendered without reflecting this change.
04/29/2004
34
34
Lifecycle of JSF Page? A JSF page is represented by a tree of UI
components, called a view? When a client makes a request for the page, the
lifecycle starts? During the lifecycle, JSF implementation must
build the view while considering state saved from the previous postback
? When the client performs a postback of the page, JSF implementation must perform lifecycle steps
– validation– conversion
The lifecycle of a JavaServer Faces page is similar to that of a JSP page: The client makes an HTTP request for the page, and the server responds with the page translated to HTML. However, because of the extra features that JavaServer Faces technology offers, the lifecycle provides some additional services to process a page.
A JavaServer Faces page is represented by a tree of UI components, called a view. When a client makes a request for the page, the lifecycle starts. During the lifecycle, the JavaServer Faces implementation must build the view while considering state saved from the previous postback. When the client performs a postback of the page, the JavaServer Faces implementation must perform several tasks, such as validate the data input of components in the view and convert input data to types specified on the server side. The JavaServer Faces implementation performs all of these tasks as a series of steps in the lifecycle.
04/29/2004
35
35
Request Processing Lifecycle
FacesRequest Reconstitute
ComponentTree
ApplyRequestValues
ProcessEvents
ProcessValidations
ProcessEvents
ResponseComplete
ResponseComplete
Render Response
ResponseComplete
ResponseComplete
FacesResponse Render
ResponderInvoke
Application
UpdateModelValues
ProcessEvents
ProcessEvents
Conversion Errors /Render Response
Validation / ConversionErrors / Render Response
The picture in this slide illustrates the steps in the JavaServer Faces request-response lifecycle.
Now let's look into each of these phases in a bit more detail.
04/29/2004
36
36
Request Processing? Life-cycle handles two types of requests
– Initial request & Postback? Initial request
– A user requests the page for the first time– Lifecycle only executes the restore view and render
response phases? Postback
– A user submits the form contained on a page that was previously loaded into the browser as a result of executing an initial request
– Lifecycle executes all phases
The life cycle handles both kinds of requests: initial requests and postbacks. When a user makes an initial request for a page, he or she is requesting the page for the first time. When a user executes a postback, he or she submits the form contained on a page that was previously loaded into the browser as a result of executing an initial request. When the life cycle handles an initial request, it only executes the restore view and render response phases because there is no user input or actions to process. Conversely, when the life cycle handles a postback, it executes all of the phases.
04/29/2004
37
37
Request Processing LifecyclePhases1.Reconstitute component tree phase2.Apply request values phase3.Process validations phase4.Update model values phase5.Invoke application phase6.Render response phase
This slide lists the major phases of request processing life cycle.
04/29/2004
38
38
greeting.jsp (from guessNumer) <HTML> <HEAD> <title>Hello</title> </HEAD> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <body bgcolor="white"> <f:view> <h:form id="helloForm" > <h2>Hi. My name is Duke. I'm thinking of a number from <h:outputText value="#{UserNumberBean.minimum}"/> to <h:outputText value="#{UserNumberBean.maximum}"/>. Can you guessit?</h2> <h:graphicImage id="waveImg" url="/wave.med.gif" /> <h:inputText id="userNo" value="#{UserNumberBean.userNumber}"> <f:validateLongRange minimum="0" maximum="10" /> </h:inputText> <h:commandButton id="submit" action="success" value="Submit" /> <p> <h:message style="color: red; font-family: 'New Century Schoolbook', serif; font-style: oblique; text-decoration: overline" id="errors1" for="userNo"/> </h:form> </f:view></HTML>
We will use greeting.jsp page as an example JSF page.
04/29/2004
39
39
Phase 1: Reconstitute Component Tree (View) Phase? When a request for a JavaServer Faces page
is made, such as when clicking on a link or a button, the JSF implementation begins the Restore view phase
– if it is the first time, an empty view is created? JSF implementation performs
– builds the view of the JavaServer Faces page – wires up event handlers and validators– saves the view in the FacesContext
When a request for a JavaServer Faces page is made, such as when clicking on a link or a button, the JavaServer Faces implementation begins the Restore View phase.
During this phase, the JavaServer Faces implementation builds the view of the JavaServer Faces page, wires up event handlers and validators, and saves the view in the FacesContext. The FacesContext object instance contains all the information needed to process a single request. All of the application's component tags, event handlers, converters, and navigators have access to the FacesContext instance.
If the page is being requested for the first time, the JavaServer Faces implementation creates an empty view during this phase. The empty view will be populated when the JSP page is processed during the lifecycle.
If the page has already been requested, a view corresponding to this page already exists. During this phase, the JavaServer Faces implementation restores the view with the state information saved on the client or the server.
04/29/2004
40
40
Example: Component Tree (View) of greeting.jsp page of GuessNumber
helloForm
userNo submit errors1
UIView
The view for the greeting.jsp page of the guessNumber example would have the UIView component at the root of the tree, with helloForm as its child and the rest of the JavaServer Faces UI components as children of helloForm.
04/29/2004
41
41
Phase 2: Apply Request Values Phase? Each component in the tree extracts its
new value from the request parameters with its built-in decode method
? Within the decode method, the value is then converted to right type then stored locally on the component
– For userNo component in greeting.jsp page, type gets converted from String to Integer
– Conversion errors are queued on the FaceContext
Once the component tree is restored, each component in the tree extracts its new value from the request parameters with its decode method. The value is then stored locally on the component. If the conversion of the value fails, an error message associated with the component is generated and queued on the FacesContext. This message will be displayed during the Render Response phase, along with any validation errors resulting from the Process Validations phase.
In the case of the userNumber component on the greeting.jsp page, the value is whatever the user entered in the field. Since the object property bound to the component has an Integer type, the JavaServer Faces implementation converts the value from a String to an Integer.
At this point, the components are set to their new values, and messages and events have been queued.
04/29/2004
42
42
Phase 3: Process Validation Phase
? JSF implementation processes all input validations registered on the components in the tree
– This is input validation (not business logic validation)? In case of validation errors
– Error messages are queued in FacesContext– Lifecycle advances directly to the Render Response
phase? Example
– userNo has be be between 1 and 10
During “Process validation” phase, the JavaServer Faces implementation processes all validations registered on the components in the tree. 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, the JavaServer Faces implementation adds an error message to the FacesContext 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 Apply Request Values, the messages for these errors are also displayed.
In the greeting.jsp page, the JavaServer Faces implementation processes the validator on the userNumber inputText tag. It verifies that the data the user entered in the text field is an integer from the range 0 to 10. If the data is invalid, or conversion errors occurred during the Apply Request Values phase, processing jumps to the Render Response phase, during which the greeting.jsp page is rendered again with the validation and conversion error messages displayed in the component associated with the messages tag.
04/29/2004
43
43
Phase 4: Update Model Values Phase
? JSF implementation walks the component tree and set the corresponding server side object properties to the components' local values
– Update the bean properties pointed at by an input component's value attribute
– Type conversion from local value to model property type
? Example in greeting.jsp– userNumber property of the UserNumberBean is
set to the local value of the userNo component
Once the JavaServer Faces implementation determines that the data is valid, it can walk the component tree and set the corresponding server side object properties to the components' local values. The JavaServer Faces implementation will only update 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 Render Response so that the page is re-rendered with errors displayed, similar to what happens with validation errors.
At this stage, the userNumber property of the UserNumberBean is set to the local value of the userNumber component.
04/29/2004
44
44
Phase 5: Invoke Application Phase
? JSF implementation handles any application-level events, such as submitting a form or linking to another page
During this phase, the JavaServer Faces implementation handles any application-level events, such as submitting a form or linking to another page.
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 FacesContext.responseComplete.
If the view being processed was reconstructed from state information from a previous request and a component has fired an event, these events are broadcast to interested listeners.
04/29/2004
45
45
Phase 5: Example in GuessNumber
? The greeting.jsp page from the guessNumber example has one application-level event associated with the UICommand component
? A default ActionListener implementation retrieves the outcome, "success", from the component's action attribute
? The listener passes the outcome to the default NavigationHandler
? The NavigationHandler matches the outcome to the proper navigation rule defined in the application's application configuration file to determine what page needs to be displayed next
? JSF implementation then sets the response view to that of the new page
The greeting.jsp page from the guessNumber example has one application-level event associated with the UICommand component. When processing this event, a default ActionListener implementation retrieves the outcome, "success", from the component's action attribute. The listener passes the outcome to the default NavigationHandler.
The NavigationHandler matches the outcome to the proper navigation rule defined in the application's application configuration file to determine what page needs to be displayed next.
The JavaServer Faces implementation then sets the response view to that of the new page. Finally, the JavaServer Faces implementation transfers control to the Render Response phase.
04/29/2004
46
46
Phase 6: Render Response Phase? JSF implementation invokes the
components' built-in encode method and renders the components from the component tree saved in the FacesContext
– Create appropriate markup from component tree– If errors in previous phases, original page is
rendered with any queued error messages? State of the response is saved so that
subsequent requests can access it and it is available to the Restore View phase
During the Render Response phase, the JavaServer Faces implementation invokes the components' encoding functionality and renders the components from the component tree saved in the FacesContext.
If errors were encountered during the Apply Request Values phase, Process Validations phase, or Update Model Values phase, the original page is rendered during this phase. If the pages contain messages tags, any queued error messages are displayed on the page.
New components can be added to the view if the application includes custom renderers, which define how to render a component. After the content of the view is rendered, the state of the response is saved so that subsequent requests can access it and it is available to the Restore View phase. The Restore View phase accesses the tree during a subsequent request.
04/29/2004
47
47
UI ComponentModel
Having a good grasp on UI component model of JSF is absolutely critical because after all JSF is all about UI component model.
04/29/2004
48
48
Sub Topics? What is a UI component?? UI component classes? UI component rendering model? Conversion model? Event and listener model? Validation model
There are several things to learn about UI component model. We already talked about some of these things but let's go over them in more detail in this segment of the presentation.
04/29/2004
49
49
UI Component Model:What is a UI Component?
First, let's learn what a UI component is.
04/29/2004
50
50
What is a UI Component?? A well defined, familiar idiom for UI design? Are configurable, reusable elements that
compose the user interfaces of JSF applications
? Can be simple, like a button, or compound, like a table, which can be composed of multiple components
? Extensible through composition, adding new components
? Accessible via JSF custom tags in JSP page, for example
JSF UI component model follows a familiar idiom for any good UI design in the sense that user interface is typically is made of various UI widgets.
JavaServer Faces UI components are configurable, reusable elements that compose the user interfaces of JavaServer Faces applications.
A UI component can be simple, like a button, or compound, like a table, which can be composed of multiple components.
UI components are extensible through composition adding new components.
By the way, UI components are not directly accessed by page authors. Instead they are accessed through JSF custom tags. This is something we will talk about again later on but this is something important to understand.
04/29/2004
51
51
JSF UI Component Model
? A set of UIComponent classes for specifying the state and behavior of UI components
? A rendering model that defines how to render the components in different ways.
? An event and listener model that defines how to handle component events
? A conversion model that defines how to plug in data converters onto a component
? A validation model that defines how to register validators onto a component
It is very important to understand the UI component model encompasses rendering mode, event and listener model, conversion model, and validation model.
JavaServer Faces technology provides a rich, flexible component architecture that includes:
* A set of UIComponent classes for specifying the state and behavior of UI components* A rendering model that defines how to render the components in different ways.* An event and listener model that defines how to handle component events* A conversion model that defines how to plug in data converters onto a component* A validation model that defines how to register validators onto a component
04/29/2004
52
52
UI Component Model:UI Component Classes
Now let's talk about actual UI component classes.
04/29/2004
53
53
UI Component Classes? UI Component classes specify all of the UI
component functionality– Retrieving values from input form (decoding)– Holding component state– Maintaining a reference to model objects – Driving event-handling– Rendering – creating markup (encoding)
JavaServer Faces technology provides a set of UI component classes, which specify all of the UI component functionality, such as holding component state, maintaining a reference to model objects, and driving event-handling and rendering for a set of standard components.
04/29/2004
54
54
UI Component Classes? JSF implementation provides a set of UI
component classes– Developers can extend these UI component
classes to create custom UI components? All JSF UI component classes extend from
UIComponentBase– UIComponentBase defines the default state and
behavior of a UIComponent
These classes are completely extensible, allowing component writers to create their own custom components.
All JavaServer Faces UI component classes extend from UIComponentBase, which defines the default state and behavior of a UIComponent.
04/29/2004
55
55
How UI Component classes are used by Page authors?? Most page authors and application
developers will not have to use these classes directly
– They will instead include the components on a page by using the component's corresponding tags
? Most of these component tags can be rendered in different ways
– For example, a UICommand component can be rendered as a button or a hyperlink using different tags
Most page authors and application developers will not have to use these classes directly. They will instead include the components on a page by using the component's corresponding tag. Most of these component tags can be rendered in different ways. For example, a UICommand can be rendered as a button or a hyperlink. Understanding this aspect of UI component class being rendered differently is very imporant.
04/29/2004
56
56
Built-in UI Component Classes? UICommand:
– Represents a control that fires actions when activated.
? UIForm: – Encapsulates a group of controls that submit data
to the application. This component is analogous to the form tag in HTML.
? UIGraphic: – Displays an image.
The set of UI component classes included in this release of JavaServer Faces are shown in this and following slides.
04/29/2004
57
57
Built-in UI Component Classes? UIInput:
– Takes data input from a user– is a subclass of UIOutput
? UIOutput: – Displays data output on a page
? UIPanel – Displays a table
? UIParameter: – Represents substitution parameters
(read slide)
04/29/2004
58
58
Built-in UI Component Classes? UISelectItem:
– Represents a single item in a set of items.? UISelectItems:
– Represents an entire set of items.? UISelectBoolean:
– Allows a user to set a boolean value on a control by selecting or de-selecting it. This class is a subclass of UIInput.
? UISelectMany: – Allows a user to select multiple items from a group
of items. This class is a subclass of UIInput.
(read slide)
04/29/2004
59
59
Built-in UI Component Classes? UISelectOne:
– Allows a user to select one item out of a group of items.This class is a subclass of UIInput.
(read slide)
04/29/2004
60
60
UI Component Model:Component Rendering
Model
We mentioned that a UI component can be rendered in different ways. So let's talk about how that can be achieved.
04/29/2004
61
61
Component Rendering? Rendering is handled by Render kit not by
component classes– Component writers can define the behavior of a
component once, but create multiple renderers? Page authors and application developers
can change the appearance of a component on the page by selecting the tag that represents the appropriate component/renderer combination
– <h:commandButton>– <h:commandLink>
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. This design has several benefits including:
* 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 component/renderer combination.
04/29/2004
62
62
RenderKit ? Defines how component classes map to
component tags appropriate for a particular client
? JSF implementation includes a built-in RenderKit for rendering to an HTML client
? For every UI component that a RenderKit supports, the RenderKit defines a set of Renderer objects
A render kit defines how component classes map to component tags appropriate for a particular client. The JavaServer Faces implementation includes a standard RenderKit class for rendering to an HTML client.
For every UI component that a render kit supports, the render kit defines a set of Renderer objects.
04/29/2004
63
63
Renderer Object ? Defines a different way to render the
particular component to the output defined by the RenderKit
? Example– UISelectOne component has three different
renderers? One of them renders the component as a set of radio
buttons? Another renders the component as a combo box. ? The third one renders the component as a list box.
Each Renderer defines a different way to render the particular component to the output defined by the render kit.
For example, a UISelectOne component has three different renderers. One of them renders the component as a set of radio buttons. Another renders the component as a combo box. The third one renders the component as a list box.
04/29/2004
64
64
UI Component Model:JSP Custom Tags inHTML Renderer Kit
Now let's talk about JSP custom tags in HTML renderer kit.
04/29/2004
65
65
Tags in HTML Renderer Kit? Each JSP custom tag defined in the standard
HTML RenderKit class is composed of – component functionality, defined in the
UIComponent class– rendering attributes, defined by the Renderer
Each JSP custom tag in the standard HTML RenderKit is composed of the component functionality, defined in the UIComponent class, and the rendering attributes, defined by the Renderer. Now let's take a look at an example in the following slide.
04/29/2004
66
66
Example Tags? <commandButton> & <commandLink> tags
– “command” defines UI component– “Button” and “Link” defines rendering attribute
For example, the two tags in the picture above both represent a UICommand component, rendered in two different ways:
The command part of the tags corresponds to the UICommand class, specifying the functionality, which is to fire an action. The button and hyperlink parts of the tags each correspond to a separate Renderer, which defines how the component appears on the page.
04/29/2004
67
67
greeting.jsp <f:view> <h:form id="helloForm" > <h2>Hi. My name is Duke. I'm thinking of a number from <h:outputText value="#{UserNumberBean.minimum}"/> to <h:outputText value="#{UserNumberBean.maximum}"/>. Can you guess it? </h2>
<h:graphic_image id="waveImg" url="/wave.med.gif" /> <h:inputText id="userNo" value="#{UserNumberBean.userNumber}" validator="#{UserNumberBean.validate}"/> <h:commandButton id="submit" action="success" value="Submit" /> <p> <h:messages style="color: red; font-family: 'New Century Schoolbook', serif; font-style: oblique; text-decoration: overline" id="errors1" for="userNo"/>
</h:form> </f:view></HTML>
Here is the new greeting.jsp page in which you can see a few custom tags. They are <h:output_text ...> and <h:inputText ..> and <h:command_button ..> tags.
04/29/2004
68
68
UI Component Model:Conversion Model
OK, let's talk about conversion model of UI component.
04/29/2004
69
69
Conversion Model? A component can be associated with
server-side model object data? Two views of the component's data:
– model view – presentation view
? Component's data can be converted between the model view and the presentation view
– This conversion is usually performed automatically by the component's renderer
– Custom conversion is supported via Converter
A JavaServer Faces application can optionally associate a component with server-side object data. This object is a JavaBeans component, such as a backing 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 and the presentation view, which represents the data in a manner that can be viewed and modified by the user.
A JavaServer Faces application must ensure that the component's data can be converted between the model view and the presentation view. This conversion is usually performed automatically by the component's renderer.
In some situations, you might want to specify a particular converter for a component's data. To facilitate this, JavaServer Faces technology includes a set of standard Converter implementations and also allows you to create your own custom Converter implementations. If you register the Converter implementation on a component, the Converter implementation converts the component's data between the two views.
04/29/2004
70
70
UI Component Model:Event & Listener Model
Now let's talk about event and listener model.
04/29/2004
71
71
JSF Event & Listener Model? Similar to JavaBeans event model
– Listener and Event classes that an application can use to handle events generated by UI components
– 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 register it on the component that generates the event
– When the user activates a component, such as by clicking a button, an event is fired
One design goal of the JavaServer Faces specification is to leverage existing models and paradigms so that developers can quickly become familiar with using JavaServer Faces in their web applications. In this spirit, the JavaServer Faces event and listener model leverages the JavaBeans architecture event model design, which is familiar to GUI developers and Web Application Developers.
Like the JavaBeans component architecture, JavaServer Faces technology defines Listener and Event classes that an application can use to handle events generated by UI components. 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 register it on the component that generates the event. When the user activates a component, such as by clicking a button, an event is fired. This causes the JavaServer Faces implementation to invoke the listener method that processes the event.
JavaServer Faces supports three kinds of events: value-change events, action events, and data-model events.
A value-change event occurs when the user changes a component value. An example is selecting a checkbox, which results in the component's value changing to true. The component types that generate these types of events are the UIInput, UISelectOne, UISelectMany, and UISelectBoolean components. Value-change events are only fired if no validation errors were detected.
An action event occurs when the user clicks a button or a hyperlink. The UICommand component generates this event.
A data model event occurs when a new row of a UIData component is selected. We will see examples of this later on in detail.
04/29/2004
72
72
UI Component Model:Validation Model
Now let's talk about validation model.
04/29/2004
73
73
Validation Model? Like the conversion model, the validation model
defines a set of standard classes for performing common data validation checks
? jsf-core tag library also defines a set of tags that correspond to the standard Validator implementations
? Most of the tags have a set of attributes for configuring the validator's properties
– minimum and maximum
JavaServer Faces technology supports a mechanism for validating a component's local data during the Process Validations phase, before object data is updated.
Like the conversion model, the validation model defines a set of standard classes for performing common data validation checks. The jsf_core tag library also defines a set of tags that correspond to the standard Validator implementations.
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.
Also like the conversion model, the validation model allows you to create your own Validator implementation and corresponding tag to perform custom validation. You can also provide a method in a backing-file bean that performs validation for a component. The component refers to this method through its validator attribute. See Performing Validation (page 864) for more information on the standard Validator implementations, how to create custom Validator implementation and validator tags, and how to reference validation code from the component tag's validator attribute.
04/29/2004
74
74
greeting.jsp <f:view> <h:form id="helloForm" > <h2>Hi. My name is Duke. I'm thinking of a number from <h:output_text value="#{UserNumberBean.minimum}"/> to <h:output_text value="#{UserNumberBean.maximum}"/>. Can you guess it? </h2>
<h:graphic_image id="waveImg" url="/wave.med.gif" /> <h:inputText id="userNo" value="#{UserNumberBean.userNumber}" validator="#{UserNumberBean.validate}"/> <h:command_button id="submit" action="success" value="Submit" /> <p> <h:messages style="color: red; font-family: 'New Century Schoolbook', serif; font-style: oblique; text-decoration: overline" id="errors1" for="userNo"/>
</h:form> </f:view></HTML>
Here is the new greeting.jsp page with the validator. The validator is specified as an red-colored attribute of <h:inputText ...> element above.
04/29/2004
75
75
ApplicationConfiguration
04/29/2004
76
76
Application Configuration File
? XML file for configuring resources required at application startup time
– navigation rules, converters, validators, render kits? Usually named as faces-config.xml? A <faces-config> tag must enclose all of
the other declarations<faces-config> ....</faces-config>
The application configuration file is an XML file, usually named faces-config.xml, whose purpose is to configure resources for an application. These resources include: navigation rules, converters, validators, render kits, and others.
The application configuration file must be valid against the DTD located at http://java.sun.com/dtd/web-facesconfig_1_0.dtd.
04/29/2004
77
77
faces-config.xml of guessNumber<?xml version="1.0"?>
<!-- Copyright 2003 Sun Microsystems, Inc. All rights reserved. SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.-->
<!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN" "http://java.sun.com/dtd/web-facesconfig_1_0.dtd">
<faces-config>
<application> <locale-config> <default-locale>en</default-locale> <supported-locale>de</supported-locale> <supported-locale>fr</supported-locale> <supported-locale>es</supported-locale> </locale-config> </application>
Here is the first part of faces-config.xml file of the guessNumber application.
04/29/2004
78
78
faces-config.xml of guessNumber <navigation-rule> ... <from-view-id>/greeting.jsp</from-view-id> ... </navigation-rule>
<navigation-rule> ... <from-view-id>/response.jsp</from-view-id> ... </navigation-rule>
<managed-bean> ... <managed-bean-name>UserNumberBean</managed-bean-name> ... <managed-bean>
</faces-config>
This is the continuation of the faces-config.xml file of the guessNumber application. Please note that the configuration file contains one or more <navigation-rule> elements and zero or more <managed-bean> elements.
04/29/2004
79
79
Application Configuration File
? You can have more than one application configuration file
? There are three ways that you can make these files available to the application]
– A resource named /META-INF/faces-config.xml in any of the JAR files in the Web application's /WEB-INF/lib directory
– A context init parameter, javax.faces.application– A resource named faces-config.xml in the
/WEB-INF/ directory of your application (most common)
You can have more than one application configuration file, and there are three ways that you can make these files available to the application. The JavaServer Faces implementation finds the file or files by looking for:
* A resource named /META-INF/faces-config.xml in any of the JAR files in the Web application's /WEB-INF/lib directory. If a resource with this name exists, it is loaded as a configuration resource. This method is practical for a packaged library containing some components and renderers. The demo-components.jar, located in <JWSDP_HOME>/jsf/samples uses this method.* A context init parameter, javax.faces.application.CONFIG_FILES that specifies one or more (comma-delimited) paths to multiple configuration files for your Web application. This method will most likely be used for enterprise-scale applications that delegate the responsibility for maintaining the file for each portion of a big application to separate groups.* A resource named faces-config.xml in the /WEB-INF/ directory of your application if you don't specify a context init parameter. This is the way most simple applications will make their configuration files available.
04/29/2004
80
80
Application Class
? When an application starts up, the JSF implementation creates a single instance of the Application class
? Is automatically created for each application
? FacesContext.getApplication()
To access resources registered with the application, you use the Application class, which is automatically created for each application. The Application class acts as a centralized factory for resources that are defined in the XML file.
When an application starts up, the JavaServer Faces implementation creates a single instance of the Application class and configures it with the information you configure in the application configuration file.
When you need to access the Application instance, the easiest way to retrieve it is to call the getApplication method of the FacesContext instance.
04/29/2004
81
81
Using JSFTag Libraries
Now let's see how JSF tag libraries are used. These tags are used by page authors. More likely these tags will be added to the JSP pages by the tool what will be used by the page authors.
04/29/2004
82
82
Two Tag Libraries
? html_basic– Defines tags for representing common HTML user
interface components? jsf_core
– Defines other JSF related tags– Independent of any rendering technology
? JSP page need to declare them<%@ taglib uri="http://java.sun.com/jsf/html/" prefix="h" %><%@ taglib uri="http://java.sun.com/jsf/core/" prefix="f" %>
JavaServer Faces technology provides two tag libraries: html_basic and jsf_core. The html_basic tag library defines tags for representing common HTML user interface components. The tags in jsf_core are independent of any rendering technology and can therefore be used with any render kit. Using these tag libraries is similar to using any other custom tag library.
To use any of the JavaServer Faces tags, you need to include these taglib directives at the top of each page containing the tags defined by these tag libraries:
<%@ taglib uri="http://java.sun.com/jsf/html/" prefix="h" %><%@ taglib uri="http://java.sun.com/jsf/core/" prefix="f" %>
The uri attribute value uniquely identifies the tag library. The prefix attribute value is used to distinguish tags belonging to the tag library. For example, the form tag must be referenced in the page with the h prefix, like this:
<h:form ...>
Make sure that you also package the html_basic and jsf_core TLDs with your application.
04/29/2004
83
83
<f:view> element
? Represents UIViewRoot component? All component tags on the page must be
enclosed in the view tag<f:view> ... other faces tags, possibly mixed with other
content ...</f:view>
? Optional locale attribute– Overrides the Locale stored in the UIViewRoot
A JavaServer Faces page is represented by a tree of components. At the root of the tree is the UIViewRoot component. The view tag represents this component on the page. As such, all component tags on the page must be enclosed in the view tag, which is defined in the jsf_core library:
<f:view> ... other faces tags, possibly mixed with other content ...</f:view>
You can enclose other content within the view tag, including HTML and other JSP tags, but all JavaServer Faces tags must be enclosed within the view tag.
The view tag has an optional locale attribute. If this attribute is present, its value overrides the Locale stored in the UIViewRoot. This value is specified as a String and must be of the form:
:language:[{-,_}:country:[{-,_}:variant]
The :language:, :country: and :variant: parts of the expression are as specified in java.util.Locale.
04/29/2004
84
84
Nested View's
? Use <f:subview> element in order to include a JSF page inside another JSP page<f:subview> jsp:include page="theNestedPage.jsp"<f:subview>
If you want to include a JavaServer Faces page within another JavaServer Faces page or another JSP page, you must enclose the entire nested page in an f:subview tag. You can add the subview tag on the parent page and nest a jsp:include inside it to include the page, like this:
<f:subview> jsp:include page="theNestedPage.jsp"<f:subview>
You can also include subview inside the nested page, but it must enclose all of the JavaServer Faces components on the nested page. The carstore application has a page called optionsPanel, which is nested inside carDetail.
04/29/2004
85
85
Using Core Tags
04/29/2004
86
86
Event Handling Tags and Attributes
? <f:actionListener> or actionListener attribute
– Registers an action listener on a component? <f:valueChangeListener> or
valueChangeListener attribute– Registers a value-change listener on a parent
component
04/29/2004
87
87
Example: <f:valueChangeListener>in customerInfo.jsp (carstore)
<h:inputText id="firstName" value="#{customer.firstName}" required="true">
<f:valueChangeListener type="carstore.FirstNameChanged" /></h:inputText>
A page author can register a ValueChangeListener on a UIInput component or a component that extends from UIInput by nesting a valuechange_listener tag within the component's tag on the page. Here is the tag corresponding to the firstName component from the customerInfo page:
<h:inputText id="firstName" value="#{customer.firstName}" required="true"> <f:valuechange_listener type="carstore.FirstNameChanged" /></h:inputText>
The type attribute of the valuechange_listener tag specifies the fully-qualified class name of the ValueChangeListener implementation.
After this component tag is processed and local values have been validated, the component instance represented by this tag will automatically queue the ValueChangeEvent associated with the specified ValueChangeListener to the component. This listener processes the event after the phase specified by the getPhaseID method of the listener implementation.
04/29/2004
88
88
Example: actionListener attributein chooseLocale.jsp (carstore)
<h:commandButton id="NAmerica" action="storeFront"
value="#{bundle.english}" actionListener="#{carstore.chooseLocaleFromLink}"></h:commandButton>
A page author can register an ActionListener on a UICommand component by nesting an action_listener tag within the component's tag on the page. Here is one of the command_link tags on the chooseLocale page, changed to reference an ActionListener implementation rather than a bean method:
<h:command_link id="NAmerica" action="storeFront"> <f:action_listener type="carstore.LocaleChange" /></h:command_link>
The type attribute of the action_listener tag specifies the fully-qualified class name of the ActionListener implementation.
When the component associated with this tag is activated, the component's decode method (or its associated Renderer) automatically queues the ActionEvent associated with the specified ActionListener to the component. This listener processes the event after the phase specified by the getPhaseID method of the listener implementation.
04/29/2004
89
89
Attribute Configuration Tags
? <f:attribute>– Adds configurable attributes to a parent
components
(Read slide>
04/29/2004
90
90
Data Conversion Tags
? <f:converter>– Registers an arbitrary converter on the parent
component? <f:convertDateTime>
– Registers a DateTime converter instance on the parent component
? <f:convertNumber>– Registers a Number converter instance on the
parent component
(Read slide)
04/29/2004
91
91
Facet Tag
? <f:facet>– Signifies a nested component that has a special
relationship to its enclosing tag
T
04/29/2004
92
92
Parameter Substitution Tag
? <f:parameter>– Substitutes parameters into a MessageFormat
instance and to add query string name/value pairs to a URL
T
04/29/2004
93
93
Tags for Representing Items in a List? <f:selectItem>
– Represents one item in a list of items in a UISelectOne or UISelectMany component
? <f:selectItems> – Represents a set of items in a UISelectOne or
UISelectMany component
T
04/29/2004
94
94
Container Tags
? <f:subview>– Contains all JavaServer Faces tags in a page that
is included in another JavaServer Faces page
T
04/29/2004
95
95
Validator Tags
? <f:validateDoubleRange>– Registers a DoubleRangeValidator on a component
? <f:validateLength>– Registers a LengthValidator on a component
? <f:validateLongRange>– Registers a LongRangeValidator on a component
? <f:validator>– Registers a custom Validator on a component
T
04/29/2004
96
96
Output Tags
? <f:verbatim>– Generates a UIOutput component that gets its
content from the body of this tag
T
04/29/2004
97
97
Using HTML Tags
04/29/2004
98
98
HTML Tags
? Used to control display data or accept data from the user
? Common attributes– id: uniquely identifies the component– value: identifies an external data source mapped to
the component's value– binding: identifies a bean property mapped to the
component instance
The tags defined by html_basic represent HTML form controls and other basic HTML elements. These controls display data or accept data from the user. This data is collected as part of a form and is submitted to the server, usually when the user clicks a button. This section explains how to use each of the component tags shown in Table 20-2, and is organized according to the UIComponent classes from which the tags are derived.
This section does not explain every tag attribute, only the most commonly-used ones. Please refer to html_basic.tld file in the <JSF_HOME>/lib directory of your download for a complete list of tags and their attributes.
In general, most of the component tags have these attributes in common:
* id: uniquely identifies the component * value: identifies an external data source mapped to the component's value * binding: identifies a bean property mapped to the component instance
The id attribute is not required for a component tag except in these situations:
* Another component or a server-side class must refer to the component * The component tag is impacted by a JSTL conditional or iterator tag
04/29/2004
99
99
Using HTML TagsUIForm & <h:form>
k.
04/29/2004
100
100
UIForm & <h:form> tag
? UIForm UI component– An input form with child components representing
data that is either presented to the user or submitted with the form
? Encloses all of the controls that display or collect data from the user
? Include HTML markup to layout the controls on the page
– <h:form> tag itself does not perform any layout
A UIForm component is an input form with child components representing data that is either presented to the user or submitted with the form. The form tag encloses all of the controls that display or collect data from the user. Here is an example:
<h:form>... other faces tags and other content...</h:form>
The form tag can also include HTML markup to layout the controls on the page. The form tag itself does not perform any layout; its purpose is to collect data and to declare attributes that can be used by other components in the form.
04/29/2004
101
101
Using HTML TagsUICommand &
<h:commandButton>
k.
04/29/2004
102
102
UICommand & <h:commandButton>? UICommand component performs an
action when it is activated– Most common renderers are Button and Link
The UICommand component performs an action when it is activated. The most common example of such a component is the button. This release supports Button and Link as UICommand component renderers.
04/29/2004
103
103
UICommand & <h:commandButton>? Additional attributes
– action: ? is either a logical outcome String or a JSF EL expression
that points to a bean method that returns a logical outcome String
? In either case, the logical outcome String is used by the navigation system to determine what page to access when the UICommand component is activated
– actionListener: ? is a JSF EL expression that points to a bean method that
processes an ActionEvent fired by the UICommand component
In addition to the tag attributes listed in Using the HTML Tags, the command_button and command_link tags can use these attributes:
* action, which is either a logical outcome String or a JSF EL expression that points to a bean method that returns a logical outcome String. In either case, the logical outcome String is used by the navigation system to determine what page to access when the UICommand component is activated * actionListener, which is a JSF EL expression that points to a bean method that processes an ActionEvent fired by the UICommand component
04/29/2004
104
104
Example1: <h:commandButton> from carDetail.jsp<h:commandButton action="#{carstore.buyCurrentCar}" value="#{bundle.buy}" /> ? action attribute
– references a method on the CarStore backing bean that performs some processing and returns an outcome
– outcome is passed to the default NavigationHandler, which matches the outcome against a set of navigation rules defined in the application configuration file.
? value attribute – references the localized message for the button's label– bundle part of the expression refers to the
ResourceBundle that contains a set of localized messages
Most pages in the carstore example use the command_button tag. When a user clicks the button, the data from the current page is processed, and the next page is opened. Here is a command_button tag from carDetail.jsp:
<h:command_button action="#{carstore.buyCurrentCar}" value="#{bundle.buy}" />
Clicking the button will cause the confirmChoices.jsp page to open. This page allows a user to fill in his name and shipping information.
The value attribute references the localized message for the button's label. The bundle part of the expression refers to the ResourceBundle that contains a set of localized messages. The buy part of the expression is the key that corresponds to the message that is displayed on the button.
The action attribute references a method on the CarStore backing bean that performs some processing and returns an outcome. The outcome is passed to the default NavigationHandler, which matches the outcome against a set of navigation rules defined in the application configuration file.
04/29/2004
105
105
Example1: buyCurrentCar() method of CarStore.javapublic class CarStore extends Object { ... public String buyCurrentCar() { getCurrentModel().getCurrentPrice(); return "confirmChoices"; } ...}
T
04/29/2004
106
106
Example1: Navigation rule for “conformChoices” in faces-config.xml
<navigation-rule> <from-view-id>/carDetail.jsp</from-view-id> <navigation-case> <description> Any action that returns "confirmChoices" on carDetail.jsp should cause navigation to confirmChoices.jsp </description> <from-outcome>confirmChoices</from-outcome> <to-view-id>/confirmChoices.jsp</to-view-id> </navigation-case> </navigation-rule>
T
04/29/2004
107
107
Example1: Resources.properties file of carstoresunroofLabel=SunroofcruiseLabel=Cruise ControlkeylessLabel=Keyless EntrysecurityLabel=Security SystemskiRackLabel=Ski RacktowPkgLabel=Tow PackagegpsLabel=GPSbuy=Buyback=BackbuyLabel=Thanks for stopping by!
T
04/29/2004
108
108
carDetail.jsp
This is carDetail.jsp page. Please note “Buy” button at the bottom of the page.
04/29/2004
109
109
confirmChoices.jsp
T
04/29/2004
110
110
Example2: <h:commandButton> from optionsPanel.jsp <h:commandButton id="Custom" value="#{bundle.Custom}" styleClass="#{carstore.customizers.Custom.buttonStyle}" actionListener="#{carstore.choosePackage}" />
? optionsPanel.jsp is “include'd” inside carDetails.jsp
M
04/29/2004
111
111
optionsPanel.jsp
T
04/29/2004
112
112
Example2: choosePackage() method of CarStore.javapublic class CarStore extends Object { ... public void choosePackage (ActionEvent event) { String packageName = event.getComponent().getId(); choosePackage(packageName); } public void choosePackage(String packageName) { // Business logic processing } ...}
T
04/29/2004
113
113
Using HTML TagsUIInput & UIOutput
k.
04/29/2004
114
114
UIInput & UIOutput Components
? UIInput component displays a value to a user and allows the user to modify this data
– The most common example is a text field? UIOutput component displays data that
cannot be modified– The most common example is a label
? Conversions can occur? Both UIInput and UIOutput components can
be rendered in several different ways
The UIInput component displays a value to a user and allows the user to modify this data. The most common example is a text field. The UIOutput component displays data that cannot be modified. The most common example is a label.
Both UIInput and UIOutput components can be rendered in several different ways. Table 21-3 lists the renderers of UIInput and UIOutput. Recall that the tags are composed of the component and the renderer. For example, the inputText tag refers to a UIInput component that is rendered with the Text renderer
04/29/2004
115
115
UIInput Component and Renderer Combinations? inputHidden
– Allows a page author to include a hidden variable in a page
? inputSecret– Accepts one line of text with no spaces and
displays it as a set of asterisks as it is typed? inputText
– Accepts a text string of one line? inputTextarea
– Accepts multiple lines of text
(Read the slide)
04/29/2004
116
116
UIOutput Component and Renderer Combinations? outputLabel
– Displays a nested component as a label for a specified input field
? outputLink– Display an <a href > tag that links to another page
without generating an ActionEvent? outputMessage
– Displays a localized message? outputText
– Displays a text string of one line
(Read the slide)
04/29/2004
117
117
Attributes of <h:inputText> and<h:outputText>? id? value? converter? validator
– JSF EL expression pointing to a backing-bean method that performs validation on the component's data
? valueChangeListener – a JSF EL expression that points to a backing- bean
method that handles the event of entering a value in this component
The following attributes, supported by both output_text and inputText, are likely to be the most commonly used:
* id: Identifies the component associated with this tag * value: Identifies the local value or an external data source, such as a backing bean property or localized message, bound to the component * converter: Identifies a converter that will be used to convert the component's local data. * validator: Is a JSF EL expression pointing to a backing-bean method that performs validation on the component's data. * valueChangeListener: Is a JSF EL expression that points to a backing- bean method that handles the event of entering a value in this component.
04/29/2004
118
118
Example: <h:inputText> in customerInfo.jsp
? <h:inputText value="#{customer.lastName}" />
Here is an example of an inputText tag from the customerInfo page:
<h:inputText value="#{CustomerBean.firstName}" />
The value attribute refers to the firstName property on the CustomerBean bean. After the user submits the form, the value of the firstName property in CustomerBean will be set to the text entered in the field corresponding to this tag.
04/29/2004
119
119
customerInfo.jsp
T
04/29/2004
120
120
Example: <h:outputText> in finish.jsp (old: need to be updated)<h:outputMessage value="#{bundle.thanksLabel}"> <f:parameter value="#{sessionScope.firstName}"/></h:outputMessage> ? value attribute specifies the MessageFormat
pattern? parameter tag specifies the substitution
parameters for the messageThanks, {0}, for using carstore. Your car will ship soon.
The output_message tag allows a page author to display concatenated messages as a MessageFormat pattern. Here is an example of an output_message tag from the finish page of the carstore application:
<h:output_message value="#{bundle.thanksLabel}"> <f:parameter value="#{sessionScope.firstName}"/></h:output_message>
The value attribute specifies the MessageFormat pattern. The parameter tag specifies the substitution parameters for the message. The value for the parameter maps to the user's first name, located in session scope. When the message is displayed in the page, the first name in the session scope replaces the {0} in the message located at the thanksLabel key in the bundle resource bundle:
Thanks, {0}, for using carstore. Your car will ship soon.
If you have more than one parameter for one message, make sure you put the parameter tags in the proper order so that the data is inserted in the correct place in the message.
A page author can also hardcode the data to be substituted in the message using the value attribute on the parameter tag.
04/29/2004
121
121
finish.jsp
T
04/29/2004
122
122
Using HTML TagsUIPanel
<h:panelGrid> &<h:panelGroup>
k.
04/29/2004
123
123
UIPanel Component
? Is used as a layout container for its children? Must have the number of rows
predetermined
A UIPanel component is used as a layout container for its children. When using the renderers from the HTML render kit, a UIPanel is rendered as an HTML table. This component differs from UIData in that UIData can dynamically add or delete rows to accommodate the underlying data source, whereas a UIPanel must have the number of rows predetermined.
04/29/2004
124
124
UIIPanelComponent and Renderer Combinations? panelGrid
– Displays a HTML table– Used to display entire table– Render attributes are
? columnClasses, columns, footerClass, headerClass, panelClass, rowClasses
? panelGroup– Groups a set of components under one parent– Used to represent rows in the tables
The panelGrid tag is used to represent entire tables. The panel_group tag is used to represent rows in the tables. To represent individual cells in the rows, the output_text tag is usually used, but any output component tag can be used to represent a cell.
The panelGrid tag has a set of attributes that specify CSS stylesheet classes: the columnClasses, footerClass, headerClass, panelClass, and rowClasses. These stylesheet attributes are not required.
The panelGrid tag also has a columns attribute. The columns attribute is required if you want your table to have more than one column because the columns attribute tells the renderer how to group the data in the table.
If a headerClass is specified, the panelGrid must have a header as its first child. Similarly, if a footerClass is specified, the panelGrid must have a footer as its last child.
04/29/2004
125
125
confirmChoices.jsp <h:panelGrid columns="2" footerClass="subtitle" headerClass="subtitlebig" styleClass="medium"
columnClasses="subtitle,medium"> <f:facet name="header"> <h:outputText value="#{bundle.buyTitle}" /> </f:facet> <h:outputText value="#{bundle.Engine}" /> <h:outputText value="#{carstore.currentModel.attributes.engine}" /> <h:outputText value="#{bundle.Brakes}" /> ... <f:facet name="footer"> <h:panelGroup> <h:outputText value="#{bundle.yourPriceLabel}" /> <h:outputText value="#{carstore.currentModel.currentPrice}" /> </h:panelGroup> </f:facet> ...</h:panelGrid>
The carstore application includes one panelGrid tag on the confirmChoices.jsp page.
This panelGrid is rendered to a table that lists all of the options that the user chose on the previous page, carDetail.
04/29/2004
126
126
confirmChoices.jsp
T
04/29/2004
127
127
Backing Bean(Model Object)Management
04/29/2004
128
128
What are Backing Beans?? Server-side objects associated with UI
components used in the page? Define UI component properties, each of
which is bound to – a component's value or – a component instance
? Can also define methods that perform functions associated with a component, which include validation, event handling, and navigation processing.
A typical JavaServer Faces application includes one or more backing beans, which are server-side objects associated with UI components used in the page. A backing bean defines UI component properties, each of which is bound to either a component's value or a component instance. A backing bean can also define methods that perform functions associated with a component, which include validation, event handling, and navigation processing.
04/29/2004
129
129
Why Backing Beans?? Separation of Model from View (MVC)
– Model handles application logic and data: Backing Beans are Model objects
– View handles presentation: UI components
Another critical function of web applications is proper management of resources. This includes separating the definition of UI component objects from objects that perform application-specific processing and hold data. It also includes storing and managing these object instances in the proper scope.
04/29/2004
130
130
How to Specify Backing Beans in JSP page?? A page author uses the JavaServer
Faces expression language (JSF EL) to bind a component's value or its instance to a backing bean property
– JSF EL is in the form of "#{...}"? A page author also uses the JSF EL to
refer to the backing-bean methods that perform processing for the component
A page author uses the JavaServer Faces expression language (JSF EL) to bind a component's value or its instance to a backing bean property. The expression must be enclosed in the curly brackets of "#{}". A page author also uses the JSF EL to refer to the backing-bean methods that perform processing for the component.
04/29/2004
131
131
Example: Binding Component Value to Backing Bean in greeting.jsp <h:inputText id="userNo" value="#{UserNumberBean.userNumber}" validator="#{UserNumberBean.validate}"/>
? userNo component's value is bound to the UserNumberBean.userNumber backing-bean property
For example, consider the inputText tag from the greeting.jsp page of the guessNumber application:
<h:inputText id="userNo" value="#{UserNumberBean.userNumber}" validator="#{UserNumberBean.validate}" />
This tag binds the userNo component's value to the UserNumberBean.userNumber backing-bean property.
04/29/2004
132
132
UserNumberBean in faces-config.xml<managed-bean> <description> The "backing file" bean that backs up the guessNumber webapp </description> <managed-bean-name>UserNumberBean</managed-bean-name> <managed-bean-class>guessNumber.UserNumberBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> <managed-property> <property-name>minimum</property-name> <property-class>int</property-class> <value>0</value> </managed-property> <managed-property> <property-name>maximum</property-name> <property-class>int</property-class> <value>10</value> </managed-property></managed-bean>
Here is the new greeting.jsp page with the validator tags (minus the surrounding HTML):
04/29/2004
133
133
Page Navigation
04/29/2004
134
Another responsibility that the application developer has is to define page navigation for the application, which involves determining which page to go to after the user clicks a button or a hyperlink. The JavaServer Faces navigation model, new for this release, is explained in Navigation Model. Navigating Between Pages (page 890) explains how to define the navigation rules for an entire application.
The application developer defines the navigation for the application in the application configuration file, the same file in which managed beans are declared.
134
Define Page Navigation? Application developer responsibility
– Navigation rules are defined in the application configuration file
? Navigation rules– Determine which page to go to after the user clicks
a button or a hyperlink
04/29/2004
135
135
Navigation Rule 1 for guessNumber Example (V1) <navigation-rule> <description> The decision rule used by the NavigationHandler to determine which view must be displayed after the current view, greeting.jsp is processed. </description> <from-view-id>/greeting.jsp</from-view-id> <navigation-case> <description> Indicates to the NavigationHandler that the response.jsp view must be displayed if the Action referenced by a UICommand component on the greeting.jsp view returns the outcome "success". </description> <from-outcome>success</from-outcome> <to-view-id>/response.jsp</to-view-id> </navigation-case> </navigation-rule>
Each navigation-rule defines how to get from one page (specified in the from-tree-id element) to the other pages of the application. The navigation-rule elements can contain any number of navigation-case elements, each of which defines the page to open next (defined by to-tree-id) based on a logical outcome (defined by from-outcome).
04/29/2004
136
136
Navigation Rule 2 for guessNumber Example (V1) <navigation-rule> <description> The decision rules used by the NavigationHandler to determine which view must be displayed after the current view, response.jsp is processed. </description> <from-view-id>/response.jsp</from-view-id> <navigation-case> <description> Indicates to the NavigationHandler that the greeting.jsp view must be displayed if the Action referenced by a UICommand component on the response.jsp view returns the outcome "success". </description> <from-outcome>success</from-outcome> <to-view-id>/greeting.jsp</to-view-id> </navigation-case> </navigation-rule>
Each navigation-rule defines how to get from one page (specified in the from-tree-id element) to the other pages of the application. The navigation-rule elements can contain any number of navigation-case elements, each of which defines the page to open next (defined by to-tree-id) based on a logical outcome (defined by from-outcome).
04/29/2004
137
(just to repeat what I just said in the previous slide)
Each navigation-rule defines how to get from one page (specified in the from-tree-id element) to the other pages of the application. The navigation-rule elements can contain any number of navigation-case elements, each of which defines the page to open next (defined by to-tree-id) based on a logical outcome (defined by from-outcome).
137
Navigation Rule? <navigation-rule>
– defines how to get from one page (specified in the from-tree-id element) to the other pages of the application
– can contain any number of <navigation-case> elements
? <navigation-case>– defines the page to open next (defined by to-tree-id)
based on a logical outcome (defined by from-outcome)
04/29/2004
138
The outcome can be defined by the action attribute of the UICommand component that submits the form, as it is in the guessNumber example:
<h:command_button id="submit" action="success" label="Submit" />
The outcome can also come from the return value of the invoke method of an Action object. The invoke method performs some processing to determine the outcome. One example is that the invoke method can check if the password the user entered on the page matches the one on file. If it does, the invoke method could return "success"; otherwise, it might return "failure". An outcome of "failure" might result in the logon page being reloaded. An outcome of "success" might result in the page displaying the user's credit card activity opening.
138
Where can Outcome come from?
? Outcome can be defined by the action attribute of the UICommand component that submits the form
? “action” attribute can be a string or action method (#{<BackingBean>.<Method>})<h:commandButton id="submit" action="success" label="Submit" /> <h:commandButton action="#{carstore.buyCurrentCar}"
value="#{bundle.buy}" />
04/29/2004
139
139
Live your lifewith Passion!
04/29/2004