JavaServerFacesForApplicationDeveloper Readonly
JavaServerFacesForApplicationDeveloper Readonly
application developers
(JSR 127, 252 & 314)
[email protected]
HTTP to a Java application server that supports servlets and JavaServer
Pages (JSP) based applications. These applications are typically form-
based, and are comprised of one or more HTML pages with which the
user interacts to complete a task or set of tasks.
[email protected]
Evolution of Web aplication’s
Design Architecture
[email protected]
Evolution of MVC Architecture
1.No MVC
[email protected]
Model 1 Architecture (Pagecentric)
[email protected]
[email protected]
Model 2 Architecture (Servletcentric)
[email protected]
Why Model 2 Architecture (instead of Model 1)?
* Solution
– 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
[email protected]
MVC Frameworks
• Struts
• JSF
• Webwork
• SpringMVC
• Tapestry
• Apache Shale
• Flex & JavaFX
• Ruby On Rails
[email protected]
Struts Vs JSF
[email protected]
Maturity
[email protected]
Controller Flexibility/Event Handling
• The heart of Struts is the Front Controller.
• Struts uses the Front Controller and Command Pattern
• A single servlet takes a request translates
HTTP parameters into a Java ActionForm, and passes
the ActionForm into a Struts Action class, which is a
command.
• The URI denotes which Action class to go to. The Struts
framework has one single event handler for the HTTP
request.
• Once the request is met, the Action returns the result
back to the front controller, which then uses it to choose
where to navigate next.
[email protected]
Controller Flexibility/Event Handling
• JSF uses the Page Controller pattern.
Although there is a single servlet every
faces request goes through, the job of the
servlet is to receive a faces page with
components. It will then fire off events for
each component and render the
components using a render toolkit.
• The components can also be bound to
data from the model.
[email protected]
Controller Flexibility/Event Handling
• JSF adds many benefits of a front controller, but
at the same time gives you the flexibility of the
Page controller.
• JSF can have several event handler on a page
while Struts is geared to one event per request.
In addition, with struts, your ActionForms have to
extend Struts classes, creating another layer of
tedious coding .
• JSF on the other hand gives developers the
ability to hook into the model without breaking
layering. Model is unaware of JSF.
[email protected]
Navigation
• Both frameworks provides declarative
navigation model and define navigation
using rules inside their XML configuration
file and supports both static navigation –
when one page flows directly to the next;
and dynamic navigation – when some
action or logic determines which page to
go it.
[email protected]
Page Development
• JSF was build with a component in mind to allow
tool developers to support RAD development.
Struts had no such vision.
• Although Struts provide custom libraries to hook
into Action Forms and offers some helper
utilities, it is geared toward a JSP and HTTP-
centric approach.
• JSF provides the ability to build components
from a variety of view technologies and does it in
such a way to be toolable.
[email protected]
Integration
• Struts was designed to be model neutral, so
there is no special hooks into a model layer.
Usually, page data must be moved from an
Action Form into another Model input format and
requires manual coding.
An ActionForm class, provides an extra layer of
tedious coding and state transition.
• JSF hides the details of any data inside the
component tree. Rich components such as data
grids can be bound to any java class. This
allows powerful RAD development,
[email protected]
Extensibility
• Both Struts and JSF provides
opportunities to extend the framework to
meet expanding requirements.
• The main hook for Struts is a
RequestProcessor class that has various
callback methods throughout the life-cycle
of request.
• Developer can extend this class to replace
or enhance the framework.
[email protected]
Extensibility
• JSF provides equivalent functionality by
allowing you to extend special life-cycle
interfaces.
[email protected]
JavaServer™ Faces (JSF) Framework Is…
[email protected]
• Environment free development
– Servlet
– Portlet
• Rendering free
– Usually HTML
– Could be not web related
[email protected]
What is JSF?
[email protected]
Why JSF?
* Standard
[email protected]
Why JSF? (Continued)
[email protected]
Why JSF?
* 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)
[email protected]
JavaServer Faces Must Be ...
* Tool friendly
* Scalable
[email protected]
How the JSF Specification Fits In
[email protected]
JSF is a UI Framework for Java Web Applications
[email protected]
JSF Architecture
[email protected]
Important Basic Capabilities
* Validation framework
* Internationalization
[email protected]
Key JSF Concepts
* UIComponent
– Render-independent characteristics
– Base class with standard behaviors
* FacesEvent
– Base class for request and application
events
* Validator
– Base class for standard and application
defined validators
[email protected]
Key JSF Concepts
* Converter
– Plug-in for String-Object conversion
* FacesContext
– Servlet request, response, session
– JSF request, response trees
– Model reference expression evaluators
[email protected]
Key JSF Concepts
* Renderer
* RenderKit
– Library of Renderers
– Extensible at runtime
– Basic HTML RenderKit is part of the specification
[email protected]
Introduction
[email protected]
JSF Projects
• MyFaces Tomahawk
• MyFaces Trinidad
• Oracle ADF Faces (Rich Client extends the
Apache Trinidad)
• ICEfaces
• Rich Faces
• MobileFaces
• Ajax4jsf
• YUI4JSF(JavaServer Faces based on Yahoo
UI library )
• Apache Shale
• JBoss Seam
[email protected]
MyFaces Tomahawk
• MyFaces provides a series of JSF components that go
beyond the JSF specification. These components are
100% compatible with the Sun JSF 1.1 Reference
Implementation (RI) or any other JSF 1.1 compatible
implementation. Of course the custom components can
also be used with the Apache MyFaces JSF
implementation.
[email protected]
MyFaces Tomahawk
• Example: <t:inputText> - This is similar to the
<h:inputText> component but it provides
additional attributes such as forceId . When this
attribute is true the HTML generated will used
the id specified by the code id/code attribute
instead of the one normally generated by
following the JSF specification.
• Converters - MyFaces components project
contains several custom objects that do not
implement UIComponent . Some of these
include objects that implement the Converter
interface.
• Tiles Support - MyFaces provides a custom
solution to allow the use of Tiles and JSF
together
[email protected]
MyFaces Trinidad
• Apache MyFaces Trinidad is a JSF framework including a
large, enterprise quality component library, supporting
critical features such as accessibility (e.g. Section 508),
right-to-left languages, etc. It also includes a set of
framework features, including:
• A dialog framework
[email protected]
Oracle ADF Faces
• Oracle ADF Faces Rich Client extends the Apache Trinidad
component framework to provide a rich set of AJAX-
enabled JSF components that radically simplifies rich
internet application development.
[email protected]
Oracle ADF Faces
• Support for Page templates, reusable page
regions, and declarative components
• Partial Page Rendering
• Advanced Data Streaming
• Support for Skinning
• Integration with ADFc to support TaskFlows
and bookmarking
• Integration with ADFm to support data
bindings.
• Oracle ADF Security Support
[email protected]
ICEfaces
• The ICEfaces Component Suite provides a complete set of
enhanced standard and custom JavaServer Faces (JSF)
components. These components provide the following
additional benefits over other JSF components:
[email protected]
RichFaces
• RichFaces is a rich component library for JSF and an
advanced framework for easily integrating AJAX
capabilities into business application development.
[email protected]
MobileFaces
• MobileFaces is a core library to extend JSF
web application to mobile devices.
[email protected]
MobileFaces
• MobileFaces is compatible with any JSF implementation.
• MobileFaces consists of
• DeviceManager
• Media Adaptor
• Content Filter
• Custom Renderkits for adapt web to mobile
• XHTML-MP, cHTML, WML, HTML
• Script Renderers
[email protected]
[email protected]
[email protected]
MobileFaces
[email protected]
Apache Shale
* Key Functionality:
View Controller
Dialog Handler
Clay Plug-In
Tiger Extensions
Remoting
* Other Features:
Application Controller
JNDI and Spring Integration
Unit Testing Framework
Struts Feature Integration
(Validator, Tiles, Token)
[email protected]
Apache Shale
* Key Functionality:
View Controller
Dialog Handler
Clay Plug-In
Tiger Extensions
Remoting
* Other Features:
Application Controller
JNDI and Spring Integration
Unit Testing Framework
Struts Feature Integration
(Validator, Tiles, Token)
[email protected]
JBoss Seam
JBoss Seam is a powerful new application framework for
building next generation Web 2.0 applications by unifying
and integrating technologies such as :
[email protected]
Ajax4JSF
Java Server Faces provided a Component Based
Architecture for building User Interface
Components for the Web Application.
Render Response
[email protected]
[email protected]
(immediate)
ValueChangeEvent
(immediate) ValueChangeEvents
ActionEvents
Apply
Restore Request Process
View Values Validations
ActionEvents
[email protected]
Application Creation
[email protected]
Application instance
• Each JSF web application has one Application Factory
[email protected]
RenderKit instance
[email protected]
Lifecycle instance
[email protected]
FaceContext instance
[email protected]
Initial Request
• When the user access the application for the first time, an initial
request is sent to the FacesServlet, which dispatches the
request to the JSF Lifecycle instance.
[email protected]
Restore View Phase
• The first phase of the JSF lifecycle is the Restore View Phase
• If the return value is null, the Restore View phase will call
renderResponse() on FacesContext for this request.
[email protected]
Restore View Phase
• The renderReponse() method will indicate that when this
phase is done, the render() method is called to execute phase.6
(Render Reponse), without proceeding with phases 2 through 5.
[email protected]
[email protected]
Render Response Phase
• When the renderResonse() method is called during the Restore
view phase, the lifecycle skips directly to the render() method,
which is responsible for performing the Render Response phase.
[email protected]
[email protected]
Render Response Phase
• Since, the JSF-specific mapping is not part of the forwarded
request, the request is ignored by the FacesServlet and
passed to the JSP container, which in turn will locate the
JSP based on the context-relative path and execute the
JSP page matching the viewId (ex., /login.jspx)
[email protected]
Render Response Phase
• The <f:view> tag is a JSP body tag that buffers all the rendered
output from the nested JSF components.
[email protected]
Render Response Phase
• For each JSF JSP tag within <f:view> during the initial render,
a JSF component is created and attached to the component
hierarchy (components are attached under UIViewRoot of
FacesContext.
[email protected]
Render Response Phase
• The process continues, and all nested components within the
HtmlForm component are rendered and added to the <f:view>
body content buffer.
• The closing tag for the <h:form> tag calls the encodeEnd()
method of the Renderer.
[email protected]
Render Response Phase
• The </f:view> end tag calls the writeState() method on the
StateManager.
• After the state has been saved, the buffer is flushed out to the
client to the client, and execution of any remaining non-JSF JSP
tags will take place. The page is now rendered in the browser.
[email protected]
[email protected]
[email protected]
[email protected]
Replacing token with serialized state and closing </f:view>
[email protected]
Restore View Phase (Postback Request)
(Postback Request)
[email protected]
Apply Request Values Phase
[email protected]
Process Validation Phase
[email protected]
Update Mode Phase
[email protected]
Invoke Application Phase
[email protected]
Postback with Navigation
[email protected]
Render Response on postback
[email protected]
JSF’s Application-related classes
Event Handling <<interface>> *
UI Components
FacesListener *
<<interface>> 1
PhaseListener
Other UI
<<interface>> <<interface>> UIComponent
Components
ActionListener ValueChangeListener
<<use>>
<<use>> <<use>>
PhaseEvent
UIViewRoot
ActionEvent ValueChangeEvent
<<instantiate>>
1
<<instantiate>>
DefaultActionListener
FacesEvent
Context
1
1
FacesContext ExternalContext
Application
<<instantiate>>
MethodBinding
Application
*
<<instantiate>>
FacesMessage
Managed/Backing ValueBinding
[email protected]
beans
Application represents a per-web-application singleton object where applications based on
JavaServer Faces (or implementations wishing to provide extended functionality) can register
application-wide singletons that provide functionality required by JavaServer Faces. Default
implementations of each object are provided for cases where the application does not
choose to customize the behavior.
The application also acts as a factory for several types of Objects specified in the Faces
Configuration file.
createComponent(java.lang.String),
createConverter(java.lang.String),
createMethodBinding(java.lang.String, java.lang.Class[]),
createValidator(java.lang.String), and createValueBinding(java.lang.String).
[email protected]
Application Instance provides access to global resources
[email protected]
FacesContext contains all of the per-request state information related to the
processing of a single JavaServer Faces request, and the rendering of the
corresponding response. It is passed to, and potentially modified by, each phase
of the request processing lifecycle.
The instance remains active until its release() method is called, after which no
further references to this instance are allowed. While a FacesContext instance is
active, it must not be referenced from any thread other than the one upon which
the servlet container executing this web application utilizes for the processing of
this request.
[email protected]
Context-related JSF classes represent the application’s
Current User-related state
Class or Package Where to get reference Description
Interface
FacesContext Javax.faces. Either passed in, or via Represents the state of the
Context FacesContext. Current request. You can get
getCurrentInstance() access to the current view,
add a new message. This is
the main entry point to JSF
API, for developing an
application.
FacesMessage Javax.faces. FacesContext. Represents a message for
Application getMessages() the current request(for
errors). FacesContext keeps
a list of messages.
Messages can be displayed
with an HtmlMessage or
HtmlMessages component.
ExternalContext javax.faces FacesContext. Provides access to the
.context getExternalContext() hosting environment, which
is either a servlet or portlet
conainer. From here, you can
get access to the underlying
session, request, response
[email protected] and so on.
The base UI component classes, and their HTML subclasses. All of them
Are in the javax.faces.component package
Class Family HTML Subclasses Description
[email protected]
The base UI component classes, and their HTML subclasses. All of them
Are in the javax.faces.component package
Class Family HTML Subclasses Description
[email protected]
The base UI component classes, and their HTML subclasses. All of them
Are in the javax.faces.component package
Class Family HTML Subclasses Description
[email protected]
The base UI component classes, and their HTML subclasses. All of them
Are in the javax.faces.component package
Class Family HTML Subclasses Description
[email protected]
Accessing Managed Beans Programmatically
[email protected]
Programatically accessing userid
currentBinding.setValue(context, “NewUserID”);
[email protected]
The entire UserBean instance can be retrieved by using the
Expression #{userBean} without any properties
(OR)
[email protected]
Invoking a method on a managed bean programmatically
MethodBinding mb = application.createMethodBinding(
“#{userBean.addConfirmedUser}”, null);
hai
try {
mb.invoke(context,null);
}
catch (EvaluationException e)
{
Throwable wrapped = e.getCause();
}
[email protected]
Using JSF Tag Libraries
[email protected]
Two Tag Libraries
1. jsf_core
– Defines other JSF related tags
– Independent of any rendering technology
2. html_basic
– Defines tags for representing common HTML
user interface components
[email protected]
Types of Core Tags
•Facet tag
•Localization tag
•Container tag
•Validator tags
[email protected]
•Output tag
Event Handling Tags and Attributes
<f:phaseListener>
– Registers a PhaseListener instance on a
UIViewRoot component
[email protected]
Example: actionListener attribute in
chooseLocale.jsp
[email protected]
Example: <f:valueChangeListener>
carstore is a pacakge
[email protected]
Attribute Configuration Tag
<f:attribute>
– Adds configurable attributes (key/value pairs) to a
parent components
[email protected]
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
[email protected]
Facet Tag
<f:facet>
– Signifies a nested component that has a special
relationship to its enclosing tag
Localization Tag
<f:loadbundle>
– Loads a resource bundle, stores properties as a
Map
[email protected]
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
[email protected]
Container Tag
<f:subview>
Output Tags
<f:verbatim>
– Generates a UIOutput component that gets its
content from the body of this tag
[email protected]
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
[email protected]
<f:view> element
<f:view>
... other faces tags, possibly mixed with other
content ...
</f:view>
[email protected]
Nested View's
<f:subview>
jsp:include page="theNestedPage.jsp"
<f:subview>
[email protected]
Using HTML Tags
[email protected]
HTML Tags
* Common attributes
– id: uniquely identifies the component
[email protected]
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
[email protected]
UICommand & <h:commandButton>
[email protected]
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
– actionListener:
<h:commandButton action="#{carstore.buyCurrentCar}"
value="#{bundle.buy}" />
*action attribute
* 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
[email protected]
Example1: <h:commandButton>
<h:commandButton action="#{carstore.buyCurrentCar}"
value="#{bundle.buy}" />
*action attribute
* 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
[email protected]
Example1: buyCurrentCar() method of CarStore.java
[email protected]
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>
[email protected]
Example1: Resources.properties
file of carstore
sunroofLabel=Sunroof
cruiseLabel=Cruise Control
keylessLabel =Keyless Entry
securityLabel =Security System
skiRackLabel =Ski Rack
towPkgLabel =Tow Package
gpsLabel =GPS
buy=Buy
back=Back
buyLabel =Thanks for stopping by!
[email protected]
<h:commandButton>
<h:commandButton id="Custom“
value="#{bundle.Custom}"
styleClass="#{carstore.customizers.Custom.buttonStyle}"
actionListener="#{carstore.choosePackage}" />
[email protected]
action vs. actionListener
action
– Designed for business logic
– Participate in navigation handling
actionListener
– Receives ActionEvent object as a parameter
– Handles user interface logic
– Does not participate in navigation
[email protected]
UIInput & UIOutput Components
[email protected]
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
* inputText
– Accepts a text string of one line
* inputTextarea
– Accepts multiple lines of text
[email protected]
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
[email protected]
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
* 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
[email protected]
<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> [email protected]
Managed beans
• Usually represent the model or the user’s
session
• Instantiated and populated by JSF
• Different scopes
– Request
– Session
– Application
[email protected]
Types of Bean Methods
• Getter and setter methods of properties
– Follows JavaBeans convention
• JSF related methods
– Validation methods
– Action event handler methods
– Value change event handler methods
– Navigation handling methods (Action
methods)
[email protected]
Managed beans
• A simple object bean
public class User
{
private String name;
<managed-bean>
<managed-bean-name>user</managed-bean-name>
<managed-bean-class>com.example.User</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
[email protected]
Managed beans
• Properties can be initialized from within faces-config.xml
<managed-bean>
<managed-bean-name>apple</managed-bean-name>
<managed-bean-class>com.example.Fruit</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>name</property-name>
<property-value>Apple</property-value>
</managed-property>
<managed-property>
<property-name>variety</property-name>
<list-entries>
<value-class>java.lang.String</value-class>
<value>Golden</value>
<value>Fuji’s</value>
<value>Granny Smith</value>
</list-entries>
</managed-property>
</managed-bean>
[email protected]
Managed beans
• Map entries can also be part of the initialization
<map-entries>
<key-class>java.lang.Integer</key-class>
<map-entry>
<key>1</key>
<value>First value</value>
</map-entry>
<map-entry>
<key>2</key>
<value>Second value</value>
</map-entry>
<map-entry>
<key>3</key>
<value>Third value</value>
</map-entry>
</map-entries>
[email protected]
Validation Methods
[email protected]
Action Event Handler Method
• Handles an ActionEvent
– Accepts an ActionEvent and returns void
• Referenced with the component's
actionListener attribute
• Only UI components that implement
ActionSource interface can refer to this method
– UICommand
– UIButton
[email protected]
Example:
chooseLocaleFromLink()
• public void chooseLocaleFromLink(ActionEvent
event) {
String current = event.getComponent().getId();
FacesContext context =
FacesContext.getCurrentInstance();
context.getViewRoot().
setLocale((Locale) locales.get(current));
resetMaps();
}
[email protected]
Action Handler (Navigation Handler) Method
[email protected]
How to reference bean methods in Custom Tags?
<h:inputText ...validator="#{CarBean.validateInput}"
valueChangeListener="#{CarBean.processValueChange}" />
[email protected]
Types of Binding
[email protected]
Binding a Component Value to a Property
• To bind a component's value to a bean
property
– You must first specify the name of the bean
and property as the value of the value attribute
using a JSF EL expression #{X.Y}
• X is value of <managed-bean-name>
• Y is value of <property-name>
– Bean and its properties are declared in
Application Configuration File (faces-config.xml)
[email protected]
• Calling page
<h:outputText value="#{CarBean.carName}" />
[email protected]
Reasons for Binding a Component Value to
a Bean Property
[email protected]
Reasons for Binding a UI Component
Instance to a Bean Property
• Calling page
<inputText
binding="#{UserNumberBean.userNoComponent}" />
• Bean class
UIInput userNoComponent = null;
...
public void setUserNoComponent(UIInput
userNoComponent) {
this.userNoComponent = userNoComponent;
}
public UIInput getUserNoComponent() {
return userNoComponent;
}
[email protected]
Example:
• Calling page (bookcashier.jsp)
<h:selectBooleanCheckbox
id="fanClub"
rendered="false"
binding="#{cashier.specialOffer}" />
• Implicit objects
– applicationScope
– cookie
– facesContext
– header
– headerValues
– initParam
– param
– paramValues
– requestScope
– sessionScope
[email protected]
Example: Binding to Implicit Object
• Calling page
<h:outputText id=version
value="#{initParam.versionNo}“
• web.xml file
<context-param>
<param-name>versionNo</param-name>
<param-value>1.05</param-name>
</context-param>
[email protected]
Managed Bean vs Backing Bean
[email protected]
Managed Bean vs. Backing Bean
[email protected]
Managed Bean vs. Backing Bean
<h:inputText
binding="#{BackingBean.someUICommandInstance}
" ... />
[email protected]
Managed Bean vs. Backing Bean
<h:inputText
binding="#{BackingBean.someUICommandInstance}
" ... />
[email protected]
Navigating between Pages
[email protected]
What is Navigation Model?
[email protected]
How Does It Work?
[email protected]
3.The ActionListener retrieves an outcome--
such as "success" or "failure"--from the
component generating the event
[email protected]
Example: Navigate from /logon.jsp based
on outcome of #{LogonForm.logon}
<navigation-rule>
<from-view-id>/logon.jsp</from-view-id>
<navigation-case>
<from-action>#{LogonForm.logon}</from-action>
<from-outcome>success</from-outcome>
<to-view-id>/storefront.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-action>#{LogonForm.logon}</from-action>
<from-outcome>failure</from-outcome>
<to-view-id>/logon.jsp</to-view-id>
</navigation-case>
</navigation-rule>
[email protected]
<navigation-rule> Element
* <from-view-id>/cars/*</from-view-id>
[email protected]
<navigation-case> Element and its Child Elements
[email protected]
Redirection
[email protected]
Navigation
• Controlled by JSF
– Each action results in a string (outcome) leading to a
new view ruled by faces-config.xml
• From-view-id is optional
• Wildcards * can be used in from-view-id
• </redirect> is optional and is only used to display the
new URL (/welcome.jsp in our case)
<navigation-rule>
<from-view-id>/ask*</from-view-id>
<navigation-case>
<from-outcome>display</from-outcome>
<to-view-id>/welcome.jsp</to-view-id>
</redirect>
</navigation-case>
</navigation-rule>
[email protected]
Navigation
• Static
– <h:commandButton
action=“display”/>
• Dynamic
– <h:commandButton
action=“#{user.doSomething}”/>
[email protected]
JSF expressions
• Invoke the property getter or setter of a
managed bean attribute
– value=“#{managedBeanName.propertyName}”
[email protected]
JSF expressions
• Operators
– Arithmetic
• - + * / div % mod
– Relational
• == != < > <= >- eq ne lt gt ge
– Logical
• && || ! and or not
– Empty
• Empty (true for null, empty strings, empty arrays,
empty map, empty else, false otherwise)
[email protected]
JSF expressions
• Examples
– ${10+3/2}
– ${10 >= 12}
– ${user.age >= 18)
– ${!(empty user.username)}
– ${(user.name == “toto”) ? “Toto” :
“Someone else”}
[email protected]
Component Tree
• Created at Restore and View phase
• Access to each page components
• Component dynamic creation
• Access to each components in model
[email protected]
Component Tree
[email protected]
Component Tree
HtmlForm
<h:form>
HtmlInputText HtmlCommandButton
<h:inputText> <h:commandButton>
[email protected]
Component Tree
• Components can be altered
– UIViewRoot component can be obtained
• FacesContext.getViewRoot();
– Components can be created
• FacesContext.
getApplication().
createComponent(
HtmlOutputText.COMPONENT_TYPE);
– Modified
• component.setValue(“newValue”);
[email protected]
Component Tree
• Tree can be modified and viewed
– UIComponent.add(UIComponent);
– UIComponent
UIComponent.getParent();
• Programmer has full access to
customize the components at runtime
– FacesContext.
getApplication().
createMethodBinding(...);
[email protected]
Component Tree
[email protected]
Component Tree
• The listener implementation retrieves the parent
of the triggered component and adds to the form
component a new child component on the fly
public void addComponent(ActionEvent actionEvent)
{
Application application = FacesContext.getCurrentInstance().
getApplication();
UIComponent form = event.getComponent().getParent();
UIComponent newOutput = application.
createComponent(
HtmlOutputText.COMPONENT_TYPE);
newOutput.setValue(”New Output Text”);
form.add(newOutput);
...
}
[email protected]
Component Tree
public void addComponent(ActionEvent actionEvent)
{
Application application = FacesContext.getCurrentInstance()
.getApplication();
[email protected]
View
• Taglib
– http://java.sun.com/jsf/html (common prefix:h)
– http://java.sun.com/jsf/core (common prefix:f)
• Most commons tags
– f:view
– h:form
– h:inputText
– h:outputText
– h:commandButton
–…
[email protected]
View
<f:view>
<html>
<head><title>Ask name</title></head>
<body>
<h:form>
Your name: <h:inputText value=“#{cart.name}”/>
<h:commandButton value=“Display Me” action=“display”/>
</h:form>
</body>
</html>
</f:view> askname.jsp
<f:view>
<html>
<head><title>Welcome</title></head>
<body>
<h:outputText value=“#{cart.name}”/>
</body>
</html>
</f:view> welcome.jsp
[email protected]
View - messages
• The faces context maintains a queue of
messages that can be created by any object
in the lifecycle
– Heavily used by Converters, Validators for errors
– Four kind
• Information
• Warning
• Error
• Fatal
[email protected]
View - messages
• To display those messages
– <h:messages/> will display all the
messages, used mostly for debugging
– <h:message for=“someId”/> will display
the error messages for the component having
“someId” as id.
[email protected]
Validation
• Server side validation
• Error notification
• Standard validators bundled with JSF:
– validateDoubleRange
• Attributes ‘minimum’ and ‘maximum’
– validateLength
• Attributes ‘minimum’ and ‘maximum’
– validateLongRange
• Attributes ‘minimum’ and ‘maximum’
[email protected]
Standard validation - usage
• To use a standard validator:
<h:inputText value=“#{user.weight}”>
<f:validateLongRange minimum=“10” maximum=“300”/>
</h:inputText>
[email protected]
Custom validation
• Implements javax.faces.validator.Validator
public void validate( FacesContext context,
UIComponent component,
Object value)
throws javax.faces.validator.ValidatorException;
• Registered in faces-config.xml
<validator>
<validator-id>org.jboss.jsf.MyValidator</validator-id>
<validator-class>org.jboss.jsf.MyValidator</validator-class>
</validator>
[email protected]
Custom validation - usage
• Three ways to use a custom validator:
• <h:inputText value=“#{user.weight}” validator=“#{user.weightValidator}” />
• <h:inputText value=“#{user.weight}”>
<f:validator validatorId=“org.jboss.jsf.MyValidator” />
</h:inputText>
• <h:inputText value=“#{user.weight}”>
<mylib:myWeightValidator minimum=“10” maximum=“300”/>
</h:inputText>
[email protected]
Conversion
• HTML fields are string
• Managed beans attributes are any object
• Need for objectstring and stringobject
conversion methods
• Standard converters bundled with JSF:
BigDecimalConverter DoubleConverter
BigIntegerConverter FloatConverter
BooleanConverter IntegerConverter
ByteConverter LongConverter
CharacterConverter NumberConverter
DateTimeConverter ShortConverter
[email protected]
Conversion - usage
• Different ways to use the converters:
• <h:inputText value=“#{user.weight}” converter=“javax.faces.Integer” />
• <h:inputText value=“#{user.weight}” converter=“user.weightConverter” />
• <h:inputText value=“#{user.weight}”>
<f:converter converterId=“javax.faces.Integer” />
</h:inputText>
• <h:inputText value=“#{user.weight}”>
<f:convertInteger />
</h:inputText>
[email protected]
Conversion - add your own
• Implements javax.faces.convert.Converter
public abstract Object getAsObject( FacesContext context,
UIComponent component,
String value)
throws javax.faces.convert.ConverterException;
<converter>
<converter-id>org.jboss.jsf.PhoneNumber</converter-id>
<converter-class>org.jboss.jsf.PhoneNumberConverter</converter-class>
</converter>
[email protected]
Events
• Three kinds
– Value change events
• Fired when an input value changed
– Action events
• Fired by command components like commandButton or
commandLink
• Typically used for user interface logic (business logic
remains in the actions)
– Phase events
• Fired by the JSF lifecycle
[email protected]
Events
• Each listener can change the lifecycle by
– Calling FacesContext.renderResponse()
– Calling
FacesContext.responseComplete()
[email protected]
Events – ValueChangeListener
• Triggered when a value changed, two ways:
– Public method with an ActionEvent parameter
• valueChangedListener=“${bean.listener}”
– Public class implementing
javax.faces.event.ValueChangeListener
• <f:valueChangeListener
type=“com.example.MyListener”/>
• public void
processValueChange(ValueChangeEvent
event)
– Can set several listeners
[email protected]
Events – ActionListener
• Triggered before an action is processed,
two ways:
– Public method with an ActionEvent parameter
• actionListener=“${bean.listener}”
– Public class implementing
javax.faces.event.ActionListener
• <f:actionListener
type=“com.example.MyListener”/>
• public void processAction(ActionEvent
event)
– Can set several listeners
[email protected]
Components
• Fast development
• Available on the web open source or not
– MyFaces: Tomahawk
• Calendar
• Tree view
• Tabbed panel
• File upload
• …
–…
[email protected]
Custom component
• For better reusability
• Minimal requirements:
– Definition in TLD of the new tag
– Reference the component in faces-
config.xml
– Tag class extending UIComponentTag
– UI class extending UIComponentBase
element
[email protected]
Custom component - Taglib
• To add a custom converter to a taglib:
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>myTaglib</short-name>
<uri>http://example.com/jsftaglib</uri>
<tag>
<name>mytag</name>
<tag-class>com.example.MyTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>text</name>
<required>true</required>
</attribute>
</tag>
</taglib>
[email protected]
Custom component – faces-
config.xml
• To reference the new component
<component>
<component-type>com.example.myComponentRef</component-type>
<component-class>com.example.UIMyTag</component-class>
</component>
[email protected]
Custom component – Tag
class
public class MyTag extends UIComponentTag
{
private String text;
public String getText() { return text;}
public void setText(String text) { this.text = text; }
[email protected]
Custom component – UI class
public class UIMyTag extends UIComponentBase
{
public void encoding(FacesContext context) throws IOException {
String text = (String)getAttributes().get(“text”);
[email protected]
Facelets
[email protected]
JSF and JSP
[email protected]
JSF and JSP (Advantages)
[email protected]
JSF and JSP (Disadvantages)
[email protected]
JSF & JSP
JSF 1.1 - Initial request (e.g. index.jsf)
[email protected]
Facelets
• A viewhandler purely created for JSF
• No more JSP
• .xhtml instead of .jsp
• No tld files and no tag classes to defined a
UIComponent
• Faster than using JSP&JSF
• JSF 2 also provides a powerful mechanism
called composite components, which builds on
Facelets' templating features
[email protected]
Migrating from JSP to Facelets
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
[email protected]
Facelets Installation
• Add jsf-facelets.jar to the classpath
• Add viewhandler config to faces-config.xml
• Change javax.faces.DEFAULT_SUFFIX to.xhtml
[email protected]
*.taglib.xml
[email protected]
Jsfc
• Jsfc : jwcid concept in Tapestry
<h:commandButton id=“btn_save” value=“Save”
action=“#{bean.method}” />
[email protected]
Inline Text
• Inline Text: Display texts without a UIComponent
<h:outputText
value=“#{IndexPageBean.welcomeMessage}” />
<h1>#{IndexPageBean.welcomeMessage}</h1>
[email protected]
Support for Unified EL
[email protected]
Templating
userInfo.xhtml
myfacelets.taglib.xml
<tag>
<tag-name>userInfo</tag-name>
<source>tags/userInfo.xhtml</source>
</tag>
Use as;
<ds:userInfo user="#{myBean.currentUser}"/>
[email protected]
EL Functions
• MyFunctions.java
myfacelets.taglib.xml
<function>
<function-name>length</function-name>
<function-class>faceletsbox.utils.CustomerUtils</function-class>
<function-signature>
java.lang.String length(java.lang.String)
</function-signature>
</function>
Use as;
• ƒÞ #{ds:length(MyBean.userName)}
[email protected]
JSTL Support
myfacelets.taglib.xml
<tag>
<tag-name>if</tag-name>
<handler-class>mycompany.myproject.utils.IfHandler
</handler-class>
</tag>
Use as;
<ds:if test="#{MyBean.isLoggedIn}"> Welcome </ds:if>
[email protected]
List of built-in Facelets tags
<ui:composition/>
<ui:decorate/>
<ui:define/>
<ui:include/>
<ui:insert/>
<ui:param/>
[email protected]
List of built-in Facelets tags
<ui:component/>
<ui:debug hotkey="p" rendered="true"/>
<ui:fragment/>
<ui:remove/>
<ui:repeat/>
[email protected]
TagHandlers Components Other
c:forEach f:validator
c:choose ui:repeat f:converte
c:set ui:fragment r
c:if ui:component
f:facet f:view
f:actionListener f:verbatim
f:valueChangeListene f:selectItems
r h:inputText
ui:include h:datatable
ui:decorate any custom
ui:composition UIComponent
any custom tag file
[email protected]
TagHandlers vs Components
[email protected]
My c:if always evaluates to false
[email protected]
Solution: replace the c:if with:
[email protected]
ui:composition :The UI Composition tag is a templating tag that wraps content
to be included in another Facelet.
Example:
<p><strong>template.jsf</strong></p>
<h2><ui:insert name="title" /></h2><p>
ui:composition
<strong>composition.jsf</strong></p>
This text will be ignored.
<ui:composition template="template.jsf">
<ui:define name="title">Hello World!</ui:define>
</ui:composition>
This text will be ignored.HTML Output
Tag Attributes
Example:
Tag Attributes
hotkey String
The key to press with 'CTRL' + 'SHIFT' to display the debug popup
window. The default value is CTRL + SHIFT + D. This attribute does
not accept EL expressions.
rendered String
<p><strong>decorate.jsf</strong></p>
Text before will stay.<br />
<ui:decorate template="template.jsf">
<ui:define name="title">Our Products</ui:define>
<ui:define name="body">
<ul>
<li>Apples</li>
<li>Oranges</li>
<li>Bananas</li>
</ul>
</ui:define>
</ui:decorate>
Text after will stay. [email protected]
ui:define
The Define tag is a templating tag that defines named content to be
inserted into a template. The name attribute value must match that
of a ui:insert tag in the target template for the named content to
be included.
Example:
<h:outputText value="#{dateBean.today}">
<s:convertDateTime dateStyle="full" type="both" />
</h:outputText><p><strong>template.jsf</strong></p>
<h2><ui:insert name="title" /></h2>
<p><strong>template.jsf</strong></p>
<ui:composition template="template.jsf">
<ui:define name="title">Hello World!</ui:define>
</ui:composition>HTML Output
<p><strong>composition.jsf</strong></p>
<h2>Hello World!</h2>
[email protected]
ui:component
The UI Component tag inserts a new UIComponent instance into the JSF
component tree. Any components or content fragments outside this tag will be
ignored by the Facelets view handler.
Any components or content fragments within this tag will be added to the
component tree as children of the UIComponent instance.
Example:
<div>Hello World!</div>
Tag Attributes
binding String
Example:
<p><strong>fragment.jsf</strong></p>
This text will be included.
<ui:fragment binding="#{myBackingBean.component}">
</ui:fragment>
<div id="message">Hello World!/div>
This text will be [email protected]
ui:include
The UI Include tag is a server-side include tag for Facelets. It simply
includes the document pointed to by the "src" attribute as part of the
current JSF page. The included document should use a component or
composition
tag to trim unnecessary markup, or it may simply contain a fragment of
XHTML
or XML to be included.
Example:
<p><strong>include.jsf</strong></p>
<ui:include src="header.jsf"/>
Body text here.HTML Output
<p><strong>include.jsf</strong></p>
<h2>Our Company</h2>
Body goes here. [email protected]
ui:insert
The UI Insert tag is a templating tag that declares a named content
element
to be defined by another Facelet. It can be used effectively with the
ui:define tag to pass values between Facelets.
Tag Attributes
1. name - String
The name attribute specifies the name of the matching ui:define tag
that will provide the content to be inserted into this Facelet.
[email protected]
ui:param
The UI Param tag is used to pass objects as named variables between
Facelets. The name attribute of the UI Param tag should match the
name attribute of a ui:define tag contained in a ui:composition or
ui:decorate in the template page receiving the object. The UI Param
tag can also be used to pass objects to another page by using the
ui:include tag.
Example:
<p><strong>param.jsf</strong></p>
<ui:include src="hello.jsf">
<ui:param name="greeting" value="#{helloBean.message}"/>
</ui:include>
HTML Output
<p><strong>param.jsf</strong></p>
<h2>Hello World</h2>
[email protected]
ui:remove
The UI Remove tag is used to specify tags or blocks of content that should be
removed from your page by the Facelets view handler at compile time.
This tag has no attributes. You can use this tag within the "jsfc" attribute to
indicate that a particular tag should be removed from the rendered page.
Note that the Facelets compilation process is much faster than the JSP compilation
process because no Java bytecode is actually generated and compiled behind the
scenes when you first visit your page.
This gives you some flexibility to display content and to work with markup in your
design environment that will be omitted once the page is actually viewed by your
users. FaceletsTools will not display any markup that is wrapped with a ui:remove
tag in Dreamweaver's design view, but it will display markup containing the "jsfc"
variant of this tag.
Example:
The UI Repeat tag is used to iterate over a collection of objects exposed to the
JSF page as a value-binding EL expression. It is intended as a replacement for
the c:forEach tag from the JSTL Core tag library.
You can also use this tag with the "jsfc" feature in Facelets.
Tag Attributes
1. value String
Required
The value attribute specifies the value-binding EL expression that resolves to
a List of objects to be iterated over.
2. var String
Required
The var attribute specifies the literal name of the variable used to iterate
over the collection.
[email protected]
uii:componsition vs ui:decorate
[email protected]
Javax.faces.application.ViewHandler Javax.el.ElContext
+renderView(context:FaceletContext,
root:UIViewRoot)
Faceletcontext
FaceletViewHandler
+buildView(context:FaceletContext, SAXCompiler
root:UIViewRott)
<<singleton>>
DefaultFaceletFactory Compiler <<interface>>
FaceletFactory
com.sun.facelets.
•location : URL tag.TagLibrary
•refreshPeriod : long
+getFacelet(uri:string) : Facelet
0..*
Facelet
+apply(context:FaceletContext,
component:UIComponent)
<<interface>>
root GaceletHandler
DefaultFacelet
+apply(context:FaceletContext, component:UIComponent()
[email protected]
UML class diagram of the core Facelets Architecture
1. During the Render lifecycle phase, the renderView() method is called on
the ViewHandler. This method takes the argument UIViewRoot, which
in the case of an initial request has no children, and does two things
with it :
[email protected]
3. In buildView(), the FaceletViewHandler calls its FaceletFactory
to create an instance of the root Facelet for this ViewID.
The implementations of this process is handled by the
DefaultFaceletFactory instance. This class performs the
loading of the XHTML file and compiles it using the Compiler.
5. Compiler uses the SAX API provided by the java to parse the
XML file. The Compiler contains a list of TagLibrary instances
for the application. This list will always include the standard
Facelets tag libraries, plus any additional ones in use by the
application.
[email protected]
6. With the tree of Facelet instances, the buildView() method simply
calls apply() on the root Facelet, passing the UIViewRoot.
This will cause the UIViewRoot to be populated, thus
accomplishing requirement 1 of renderView().
[email protected]
Creating Composition Components
<custom:inputTextLabeled
label="Name"
value="#{bird.name}" />
[email protected]
InputTextLabeled.xhtml
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<ui:component>
<h:outputLabel value="#{label}: ">
<h:inputText value="#{value}"/>
</h:outputLabel>
</ui:component>
</html>
<facelet-taglib>
<namespace>http://myfaces.apress.com/custom
</namespace>
<tag>
<tag-name>inputTextLabelled</tag-name>
<source>components/InputTextLabeled.xhtml
</source>
</tag>
</facelet-taglib>
[email protected]
web.xml
<context-param>
<param-name>facelets.LIBRARIES</param-name>
<param-value>
/WEB-INF/facelets/mycustom.taglib.xml
</param-value>
</context-param>
[email protected]
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:custom="http://myfaces.apress.com/custom">
<body>
<f:view>
<h:form>
<h:panelGrid columns="1">
<custom:inputTextLabeled
label="Name" value="#{bird.name}"/>
<custom:inputTextLabeled
label="Order" value="#{bird.order}"/>
<custom:inputTextLabeled
label="Family" value="#{bird.family}"/>
<h:commandButton
value="Add Bird"
actionListener="#{birdDirectory.addBird}"/>
</h:panelGrid>
</h:form>
</f:view>
</body> [email protected]
</html>
Facelets - Summary
• Facelets saves JSF from the burden of jsp
[email protected]
Ajax4Jsf
[email protected]
What is Ajax?
•Intuitive and natural user interaction
> No clicking required
Mouse movement is a sufficient event trigger
[email protected]
What is Ajax?
• Asynchronous communication replaces
"synchronous request/response model."
> A user can continue to use the
application while the client
• program requests information from the
server in the background
> Separation of displaying from data
fetching
[email protected]
[email protected]
[email protected]
Technologies Used In AJAX
• Javascript
> Loosely typed scripting language
> JavaScript function is called when an event in a page occurs
Glue for the whole AJAX operation
• DOM
> API for accessing and manipulating structured documents
Represents the structure of XML and HTML documents
• CSS
> Allows for a clear separation of the presentation style from the
content and may be changed programmatically by JavaScript
• XMLHttpRequest
> JavaScript object that performs asynchronous interaction with the
server
[email protected]
XMLHttpRequest
• JavaScript object
[email protected]
[email protected]
[email protected]
Steps of AJAX Operation
1.A client event occurs
2.An XMLHttpRequest object is created
3.The XMLHttpRequest object is configured
4.The XMLHttpRequest object makes an async.
request
5.The ValidateServlet returns an XML document
containing the result
6.The XMLHttpRequest object calls the callback()
function and processes the result
7.The HTML DOM is updated
[email protected]
1. A Client event occurs
[email protected]
3. An XMLHttpRequest object is configured with a callback function
var req;
function initRequest() {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
isIE = true;
req = new ActiveXObject("Microsoft.XMLHTTP");
}
}
function validateUserId() {
initRequest();
req.onreadystatechange = processRequest; // callback function
if (!target) target = document.getElementById("userid");
var url = "validate?id=" + escape(target.value);
req.open("GET", url, true);
req.send(null);
}
[email protected]
4. XMLHttpRequest object makes an async. request
function initRequest() {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
isIE = true;
req = new ActiveXObject("Microsoft.XMLHTTP");
}
}
function validateUserId() {
initRequest();
req.onreadystatechange = processRequest;
if (!target) target = document.getElementById("userid");
var url = "validate?id=" + escape(target.value);
req.open("GET", url, true);
req.send(null);
}
[email protected]
5. The ValidateServlet returns an XML document containing the results
(Server)
[email protected]
6. XMLHttpRequest object calls callback()
function and processes the result
• The XMLHttpRequest object was configured to
call the processRequest() function when there
is a state change to the readyState of the
XMLHttpRequest object
function processRequest() {
if (req.readyState == 4) {
if (req.status == 200) {
var message = ...;
...
[email protected]
Filter Settings for web.xml
<?xml version="1.0"?>
<web-app ...>
...
<filter>
<display-name>Ajax4jsf Filter</display-name>
<filter-name>ajax4jsf</filter-name>
<filter-class>org.ajax4jsf.Filter</filter-class>
</filter>
<filter-mapping>
<filter-name>ajax4jsf</filter-name>
<servlet-name>Faces Servlet</servlet-name>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>
</web-app>
[email protected]
Tag Summary
• a4j:poll
– Run code periodically on server, then update specified
JSF element(s)
• a4j:support
– Capture JavaScript event in any existing JSF control and
invoke server-side code, then update specified element(s)
• <h:inputText ...>
<a4j:support event="onkeyup" reRender="some-id"/>
</h:inputText>
[email protected]
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="https://ajax4jsf.dev.java.net/ajax" prefix="a4j"%>
<f:view>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"" />
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
<title>Ajax4JSF Examples</title>
</head>
[email protected]
h:commandLink: Example
<tr><td width="100">
<h:form>
<a4j:commandLink
action="#{numBean.makeResult}"
value="Show Random Number"
reRender="region2"/>
</h:form>
</td>
<td width="100">
<h:outputText value="#{numBean.result}"
id="region2"/>
</td>
</tr>
[email protected]
a4j:commandButton and a4j:commandLink: faces-config
<managed-bean>
<managed-bean-name>
numBean
</managed-bean-name>
<managed-bean-class>
coreservlets.RandomNumberBean
</managed-bean-class>
<managed-bean-scope>
request
</managed-bean-scope>
</managed-bean>
[email protected]
a4j:commandButton: Example 2
<tr><td width="100">
<h:form>
Range:
<h:inputText value="#{numBean.range}"
size="5"/><br/>
<a4j:commandButton
action="#{numBean.makeResult}"
value="Show Random Number"
reRender="region3"/>
</h:form>
</td>
<td width="100">
<h:outputText value="#{numBean.result}"
id="region3"/>
</td>
[email protected]
a4j:poll: Basic Syntax
<a4j:poll
interval="x"
reRender="some-id"/>
• Interpretation
– Every x milliseconds, send off an asynchronous HTTP request to the server.
– Re-evaluate and re-display the JSF element with the id some-id.
• Key point: this element should result from code that gives different values
at different times
• Unlike with a4j:commandButton, there is no explicit additional server-side
method to run
[email protected]
a4j:poll: Bean
[email protected]
JavaScript Event Handlers used with a4j:support
• onchange
– User changes element (IE: and element loses focus)
• onclick/ondblclick
– User single/double clicks form element or link
• onfocus/onblur
– Element receives/loses focus
• onkeydown/onkeypress/onkeyup
– User presses/presses-or-holds/releases a key
• onmousedown/onmouseup
– User presses/releases mouse
• onmousemove
– User moves mouse
• onmouseover/onmouseout
– User moves mouse onto/off area or link
• onselect
– User selects text within a textfield or textarea
• onsubmit
[email protected]
a4j:support: Example
<h:form>
<table border="1">
<tr><th>Textfield</th>
<th>Ajax Value</th>
</tr>
<tr><td width="100">
<h:inputText value="#{myBean.message}">
<a4j:support event="onkeyup"
reRender="output-region"/>
</h:inputText></td>
<td width="100">
<h:outputText value="#{myBean.message}"
id="output-region"/></td>
</tr>
</table>
</h:form>
[email protected]
a4j:support: faces-config.xml
<managed-bean>
<managed-bean-name>
myBean
</managed-bean-name>
<managed-bean-class>
coreservlets.MessageBean
</managed-bean-class>
<managed-bean-scope>
request
</managed-bean-scope>
</managed-bean>
[email protected]
a4j:support: Example 2
• Idea
– Use h:selectOneMenu to make a list of US states
– When the user selects a state, a list of corresponding
cities is shown (again, using h:selectOneMenu)
– When city selected, population of that city is displayed
• Approach
– State list
• <a4j:support event="onchange" reRender="city-list"/>
– City List
• <a4j:support event="onchange" reRender="pop-field"/>
– Bean
• Make it session scoped so values persist across across
multiple submissions (since there are at least two)
[email protected]
a4j:support: Bean
[email protected]
a4j:support: Bean (Continued)
[email protected]
Tools and Toolkits
• Client-Side Tools
– Dojo.
• Open source JavaScript toolkit with Ajax support
• http://www.dojotoolkit.org/
– script.aculo.us
• Free JavaScript toolkit with Ajax support
• http://script.aculo.us/
[email protected]
Tools and Toolkits (Continued)
• Ajax4jsf
– http://labs.jboss.com/jbossajax4jsf/
• IceFaces
– http://www.icefaces.org/
[email protected]
Apache Shale
[email protected]
JSF and Other JSF and Other Frameworks
[email protected]
JSF Extension Points
• VariableResolver – Customize evaluation of first
token in expressions
• PropertyResolver – Customize evaluation of the “.”
operator in expressions
• NavigationHandler – Customize navigation
decisions
• ViewHandler – Customize view creation and
restoration
• PhaseListener – Participate in (and modify) the
standard request processing lifecycle
[email protected]
Shale Features
Key Functionality:
• View Controller
• Dialog Handler
• Clay Plug-In
• Tiger Extensions
• Remoting
• Other Features:
• Application Controller
• JNDI and Spring Integration
• Unit Testing Framework
• Struts Feature Integration (Validator, Tiles, Token)
[email protected]
View Controller
• A common pattern in JSF is backing bean per page
• Must know the JSF request processing lifecycle to
understand where to inject some types of
application logic
• Example – DB query needed to populate a table:
• Only want to perform the query if it will actually be used
• Skip it if the user navigated to a different page
• Example – Need a transactional resource available
through rendering, but then need to clean up
• Need to regain control after rendering is completed
[email protected]
View Controller
[email protected]
Dialog Manger
• Standard JSF navigation handler decides based on:
• What view am I currently processing?
• Which execute action method was invoked?
• What logical outcome was returned by this action?
• Issue – modeling of a “conversation” is ad hoc
• Issue – how do we deal with conversational state?
• Pass information in hidden fields
• Can be unwieldy when numerous fields are required
• Store information in session
• Occupies memory if not cleaned up
[email protected]
Dialog Manager
• Dialog Manager deals with these issues:
• Models conversations as an execution engine
• Provides storage mechanism for conversational state
• Heavily inspired by Spring Web Flow, but “JSF-ized”
• Caution – Following functionality is currently in the
• Shale sandbox, but will be imported to trunk soon
• Application uses DialogContext abstraction
• Maintain state (getData(), setData())
• Execution: start(), stop(), and advance()
• Parent dialog support (for popups)
• Start dialogs programmatically or via navigation
[email protected]
CLAY Plug-In
• JavaServer Faces mandates that standard
components support JavaServer Pages (JSP) for
view representation
• Issue – interoperability problems with template text
• Mostly resolved with JSF1.2 and JSP 2.1(part of Java EE 5)
• Issue – Reuse of portions of page layout is difficult
• Can be addressed by JSF components focused
on this need
• Issue – Some developers prefer a more “pure”
HTML representation of the view portion of an
application
[email protected]
CLAY Plug-In
• Clay enables grafting a component subtree onto an
existing component tree
• Sounds simple, but provides compelling features:
HTML Views – Can separate views into pure HTML
• pages, with pointers to component definitions
• Similar capabilities found in Tapestry and Facelets
• Metadata Inheritance – Component definitions can
extend previous definitions:
• Similar in spirit to how Tiles can extend other Tiles
• Create reusable “components” with no Java coding
• Symbol Replacement – Customize managed bean
names
[email protected]
Clay Plug-In – JSP Login Page
<h:form>
<table border=”0”>
<tr><td>Username:</td>
<td><h:inputText id=”username”
value=”#{logon.username}”/></td></tr>
<tr><td>Password:</td>
<td><h:inputSecret id=”password”
value=”#{logon.password}”/></td></tr>
<tr><td><h:commandButton id=”logon”
action=”#{logon.authenticate}”></td></tr>
</table>
</h:form>
[email protected]
Clay Plug-In – Clay Login
<form jsfid=”logonForm”>
<table border=”0”>
<tr><td>Username:</td>
<td><input type=”text” name=”username”
jsfid=”username”/></td></tr>
<tr><td>Password:</td>
<td><input type=”password” name=”password”
jsfid=”password”/></td></tr>
<tr><td><input type=”submit” value=”Log On”
jsfid=”logon”/></td></tr>
</table>
</form>
[email protected]
Clay Plug-In –Clay Components
<component jsfid=”username”
extends=”inputText”
id=”username”>
<attributes>
<set name=”required” value=”true”/>
<set name=”value”
value=”#{logon.username}”/>
</attributes>
</component>
[email protected]
Clay Plug-In
• So why do I want this?
• Pure HTML can be easily built with standard HTML editors
• Graphic artist can include “sample” data that will be replaced
<table jsfid=”addressList”>
... dummy columns and data values ...
</table>
• Four general strategies are supported:
• Strictly XML that uses composite components (addressForm)
• Tapestry style separate HTML (as illustrated above)
• Subtree dynamically built at runtime (<clay:clay> tag)
• Pure XML similar to the separate HTML approach
[email protected]
Remoting
• It is common for applications to respond to
programs as well as to humans:
• Web services
• AJAX-based asynchronous requests
• Shale provides features to make this easier:
• For application developers
• For JSF component authors
• Packaged as a small (40k) JAR, only needs JSF
• Zero configuration if you accept the defaults
• Implemented as a JSF PhaseListener
[email protected]
Other Shale Features
• Application Controller
• Configured as a servlet filter
• Supports decoration of the request processing lifecycle
• Uses “chain of responsibility” design pattern (Commons Chain)
• Similar in spirit to customizing request processor in Struts
• JNDI and Spring Integration:
• Custom JSF variable and property resolvers
• Transparent access to JNDI contexts and Spring created
beans, via EL expressions
• Unit testing framework:
• Mock objects for building unit tests
[email protected]
Other Shale Features
• Struts Functionality Equivalents:
• Commons Validator for client side validation
• Implemented as a JSF validator
• Tiles Support
• Based on “standalone” version of Tiles being developed
• No dependency on Struts
• Can navigate to a view or to a tile
• Transaction token support
• Prevent duplicate submits of a form
• Implemented as a component that fires validation
failures on duplicate submits
[email protected]
JBoss Seam
[email protected]
[email protected]
[email protected]
JSF Design Patterns
[email protected]
Singleton pattern
[email protected]
Factory Method pattern
• The purpose of the Factory Method pattern is to define an interface
for creating an object but deferring instantiation of the object to
subclasses.
• In the JSF architecture, the Factory Method pattern is used to
create objects. LifeCycleFactory is a factory object that creates and
returns LifeCycle instances. The getLifeCycle (String LifeCycleId)
method of LifeCycleFactory is a Factory Method pattern that creates
(if needed) and returns LifeCycle instances based on LifeCycleId.
• For every JSF request, FacesServlet gets FacesContext from
FacesContextFactory. FacesContextFactory is an abstract class
that exposes the getFacesContext API, and JSF implementation
provides concrete implementation of the FacesContextFactory and
getFacesContext API. This is another example of the Factory
Method pattern where concrete FacesContextFactory creates
FacesContext objects.
[email protected]
State Pattern
• The intent of the State pattern is to distribute state-
specific logic across different classes that represent
states.
• FacesServlet invokes execute and render methods on a
LifeCycle instance. LifeCycle collaborates with different
Phases in order to execute a JSF request. JSF
implementation follows the State pattern here.
• JSF implementation creates separate classes of each
state (or phase) and invokes steps. A phase is an
abstract class that defines the common interface for
every step. In the JSF framework, six phases, or steps,
are defined: RestoreViewPhase, ApplyRequestValues,
ProcessValidationsPhase, UpdateModelValuesPhase,
InvokeApplicationPhase, and RenderResponsePhase.
[email protected]
State Pattern
• As in the State pattern, LifeCycle passes a FacesContext object to the
phases. Each phase or state changes the contextual information passed to
it and then sets the flag in the FacesContext itself to indicate the next
possible step. JSF implementation alters its behavior with each step.
• Each phase can be responsible for the next phase. FacesContext has two
flags -- renderResponse
• After execution of each step, LifeCycle checks whether either of these flags
was set by the previous phase. If a responseComplete is set, LifeCycle
abandons the execution of the request altogether. If a renderResponse flag
is set after some phase,
• JSF implementation skips remaining phases and goes directly to the render
response phase. If neither flag is set, LifeCycle executes the next step in the
sequence.
[email protected]
Composite Pattern
• The Composite pattern allows clients to deal with composite and
primitive objects uniformly. A composite object is a container for
primitive objects.
• In the first phase (Restore View phase) and the last phase (Render
Response phase), the UI View is constructed using JSF UI
components.
[email protected]
Strategy Pattern
• The delegated implementation model is more flexible
than direct implementation and leverages the Strategy
design pattern. In the Strategy pattern, you encapsulate
an algorithm that varies into a separate object so the
algorithm can be varied dynamically.
[email protected]
Template Pattern
• The Template Method pattern's intention is to
defer variant steps to the subclasses while the
parent class defines invariant steps of the
algorithm.
• The JSF framework offers functionality provided
by the Template Method pattern through
PhaseListeners.
• Template Method (or "hook") is implemented so
Web authors can provide implementation for the
optional steps between phases while main
phases remain the same as defined by the JSF
framework.
[email protected]
Template Pattern
• The JSF framework provides PhaseListeners
that are conceptually similar to variant steps of
the Template Method pattern.
• The JSF framework has six predefined phases,
and between each phase, a Web author can
implement PhaseListeners to provide hooks
similar to the Template Method hooks.
• In fact, this is much more extensible than the
Template Method pattern.
• You can provide hooks after each phase by
registering a PhaseListener that has PhaseId of
ANY_PHASE value.
[email protected]
Template Pattern
• If the PhaseId is ANY_PHASE, the JSF
implementation calls the PhaseListener before
and after every phase.
[email protected]
Observer Pattern
• The intent of the Observer pattern is to notify all dependent objects
(or observers) automatically when the state in the subject changes.
[email protected]
EditableValueHolder
• ValueHolder is an interface that may be implemented by any
concrete UIComponent that wishes to support a local value, as well
as access data in the model tier via a value binding expression, and
support conversion between String and the model tier data's native
data type.