Javaserver Faces (JSF) Basics
Javaserver Faces (JSF) Basics
Topics
Evolution of Web Application Framework 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
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
3
Historical Background
4
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
5
Background
4
Response
JSP pages
2 3
BROWSER
Java Bean
Servlet Container
10
Page-centric Architecture
memu.jsp
catalog.jsp
checkout.jsp
One page might display a menu of options, another might provide a form for selecting items from the catalog,and another would be to complete shopping process
This doesn't mean we lose separation of presentation and content Still use the dynamic nature of JSP and its support for JavaBeans component to factor out business logic from presentation The pages are tightly coupled:
Need to sync up request parameters Be aware of each other's URLs
12
(Controller) Servlet
Redirect 3
In
BROWSER
5
Response
st a nt i at e
(View) JSP
Servlet Container
(EIS)
14
What if you want to present different JSP pages depending on the data you receive?
JSP technology alone even with JavaBeans and custom tags (Model 1) cannot handle it well Use Servlet and JSP together (Model 2) Servlet handles initial request, partially process the data, set up beans, then forward the results to one of a number of different JSP pages
Solution
15
16
What is JSF?
Why JSF?
MVC for web applications Clean separation of roles Extensible Component and Rendering architecture Support for client device independence Standard Huge vendor and industry support
19
UI-component and Web-tier concepts without limiting you to a particular scripting technology or markup language
Why JSF?
No built-in UI component model I am not saying you should not use Struts Struts and JSF can be used together 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)
Struts
21
22
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
23
JS F API
S ervlets (2.3)
24
Client
( event s)
Response
( ar m kup)
26
JSF Architecture
Server
JSF Page
Desktop Browser
Fr ont ctl r
App Backend
Phone
WML
27
Extensible UI component model Flexible rendering model Event handling model Validation framework Basic page navigation support Internationalization Accessibility
28
UIComponent
Render-independent characteristics Base class with standard behaviors UICommand, UIForm, UIGraphic, UIInput, UIOutput, UIPanel, UISelectBoolean, UISelectMany, UISelectOne Base class for request and application events Base class for standard and application defined validators
FacesEvent
Validator
29
Converter
Plug-in for String-Object conversion Servlet request, response, session JSF request, response trees Model reference expression evaluators
FacesContext
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
30
Renderer
Converts components to and from a specific markup language Supports render-dependent attributes on components May support more than one component type Library of Renderers Extensible at runtime Basic HTML RenderKit is part of the specification
31
RenderKit
Servlet 2.3 (JSR-53) JSP 1.2 (JSR-53) JSTL 1.0 (JSR-52) Portals (JSR-168) Will be considered for J2EE 5.0 It is included in J2EE 1.4 SDK, however
32
Developer Roles
33
34
Roles Definition
Familiar with markup language(s) to be used Assembler of prebuilt components Uses Drag and drop IDE like Sun Java Studio Creator
Roles Definition
Application Developer Creates the serverside 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
36
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
37
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
39
Faces Request
Process Events
Process Validations
Process Events
Response Complete
Faces Response
Render Responder
Process Events
Invoke Application
Process Events
40
Request Processing
Initial request & Postback A user requests the page for the first time Lifecycle only executes the restore view and render response phases 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
41
Initial request
Postback
42
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 builds the view of the JavaServer Faces page wires up event handlers and validators saves the view in the FacesContext
44
45
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
46
JSF implementation processes all input validations registered on the components in the tree
This is input validation (not business logic validation) Error messages are queued in FacesContext Lifecycle advances directly to the Render Response phase userNo has be be between 1 and 10
47
Example
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 userNumber property of the UserNumberBean is set to the local value of the userNo component
48
Example in greeting.jsp
JSF implementation handles any application-level events, such as submitting a form or linking to another page
49
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
50
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
51
UI Component Model
52
Sub Topics
What is a UI component? UI component classes UI component rendering model Conversion model Event and listener model Validation model
53
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
55
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
56
UI Component Classes
Retrieving values from input form (decoding) Holding component state Maintaining a reference to model objects Driving event-handling Rendering creating markup (encoding)
58
UI Component Classes
59
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
For example, a UICommand component can be rendered as a button or a hyperlink using different 60 tags
UICommand:
Represents a control that fires actions when activated. Encapsulates a group of controls that submit data to the application. This component is analogous to the form tag in HTML. Displays an image.
UIForm:
UIGraphic:
61
UIInput:
Takes data input from a user is a subclass of UIOutput Displays data output on a page Displays a table Represents substitution parameters
62
UIOutput:
UIPanel
UIParameter:
UISelectItem:
Represents a single item in a set of items. Represents an entire set of items. Allows a user to set a boolean value on a control by selecting or de-selecting it. This class is a subclass of UIInput. Allows a user to select multiple items from a group of items. This class is a subclass of UIInput.
63
UISelectItems:
UISelectBoolean:
UISelectMany:
UISelectOne:
Allows a user to select one item out of a group of items.This class is a subclass of UIInput.
64
Component Rendering
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>
66
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
67
Renderer Object
Defines a different way to render the particular component to the output defined by the RenderKit Example
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.
68
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
70
Example Tags
71
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>
72
Conversion Model
A component can be associated with server-side model object data Two views of the component's data:
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
74
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
76
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
78
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>
79
Application Configuration
80
Usually named as faces-config.xml A <faces-config> tag must enclose all of the other declarations
<faces-config> .... </faces-config>
81
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>
82
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>
83
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)
84
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()
85
html_basic
Defines tags for representing common HTML user interface components Defines other JSF related tags Independent of any rendering technology
jsf_core
<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>
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>
89
90
91
92
93
<f:attribute>
94
<f:converter>
Registers an arbitrary converter on the parent component Registers a DateTime converter instance on the parent component Registers a Number converter instance on the parent component
95
<f:convertDateTime>
<f:convertNumber>
Facet Tag
<f:facet>
Signifies a nested component that has a special relationship to its enclosing tag
96
<f:parameter>
Substitutes parameters into a MessageFormat instance and to add query string name/value pairs to a URL
97
<f:selectItem>
Represents one item in a list of items in a UISelectOne or UISelectMany component Represents a set of items in a UISelectOne or UISelectMany component
<f:selectItems>
98
Container Tags
<f:subview>
Contains all JavaServer Faces tags in a page that is included in another JavaServer Faces page
99
Validator Tags
<f:validateDoubleRange>
Registers a DoubleRangeValidator on a component Registers a LengthValidator on a component Registers a LongRangeValidator on a component Registers a custom Validator on a component
100
<f:validateLength>
<f:validateLongRange>
<f:validator>
Output Tags
<f:verbatim>
Generates a UIOutput component that gets its content from the body of this tag
101
102
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
103
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
107
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 is a JSF EL expression that points to a bean method that processes an ActionEvent fired by the UICommand component
108
actionListener:
110
112
carDetail.jsp
113
confirmChoices.jsp
114
115
optionsPanel.jsp
116
117
118
UIInput component displays a value to a user and allows the user to modify this data
Conversions can occur Both UIInput and UIOutput components can be rendered in several different ways
119
inputHidden
Allows a page author to include a hidden variable in a page Accepts one line of text with no spaces and displays it as a set of asterisks as it is typed Accepts a text string of one line Accepts multiple lines of text
inputSecret
inputText
inputTextarea
120
outputLabel
Displays a nested component as a label for a specified input field Display an <a href > tag that links to another page without generating an ActionEvent Displays a localized message Displays a text string of one line
outputLink
outputMessage
outputText
121
JSF EL expression pointing to a backing-bean method that performs validation on the component's data a JSF EL expression that points to a backingbean method that handles the event of entering a value in this component 122
valueChangeListener
123
customerInfo.jsp
124
finish.jsp
126
UIPanel Component
Is used as a layout container for its children Must have the number of rows predetermined
128
panelGrid
Displays a HTML table Used to display entire table Render attributes are
panelGroup
Groups a set of components under one parent Used to represent rows in the tables
129
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>
130
confirmChoices.jsp
131
Server-side objects associated with UI components used in the page Define UI component properties, each of which is bound to
Can also define methods that perform functions associated with a component, which include validation, event handling, and navigation processing.
133
Model handles application logic and data: Backing Beans are Model objects View handles presentation: UI components
134
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
A page author also uses the JSF EL to refer to the backing-bean methods that perform processing for the component
135
136
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>
137
Page Navigation
138
Navigation rules are defined in the application configuration file Determine which page to go to after the user clicks a button or a hyperlink
Navigation rules
139
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 defines the page to open next (defined by to-treeid) based on a logical outcome (defined by fromoutcome)
142
<navigation-case>
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}" />
143
145