JavaServerFacesForApplicationDeveloper Readonly
JavaServerFacesForApplicationDeveloper Readonly
application developers
(JSR 127, 252 & 314)
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
Evolution of Web aplication’s
Design Architecture
ramana@adityahrudayam.com
Evolution of MVC Architecture
1.No MVC
ramana@adityahrudayam.com
Model 1 Architecture (Pagecentric)
ramana@adityahrudayam.com
ramana@adityahrudayam.com
Model 2 Architecture (Servletcentric)
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
MVC Frameworks
• Struts
• JSF
• Webwork
• SpringMVC
• Tapestry
• Apache Shale
• Flex & JavaFX
• Ruby On Rails
ramana@adityahrudayam.com
Struts Vs JSF
ramana@adityahrudayam.com
Maturity
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
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,
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
Extensibility
• JSF provides equivalent functionality by
allowing you to extend special life-cycle
interfaces.
ramana@adityahrudayam.com
JavaServer™ Faces (JSF) Framework Is…
ramana@adityahrudayam.com
• Environment free development
– Servlet
– Portlet
• Rendering free
– Usually HTML
– Could be not web related
ramana@adityahrudayam.com
What is JSF?
ramana@adityahrudayam.com
Why JSF?
* Standard
ramana@adityahrudayam.com
Why JSF? (Continued)
ramana@adityahrudayam.com
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)
ramana@adityahrudayam.com
JavaServer Faces Must Be ...
* Tool friendly
* Scalable
ramana@adityahrudayam.com
How the JSF Specification Fits In
ramana@adityahrudayam.com
JSF is a UI Framework for Java Web Applications
ramana@adityahrudayam.com
JSF Architecture
ramana@adityahrudayam.com
Important Basic Capabilities
* Validation framework
* Internationalization
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
Key JSF Concepts
* Converter
– Plug-in for String-Object conversion
* FacesContext
– Servlet request, response, session
– JSF request, response trees
– Model reference expression evaluators
ramana@adityahrudayam.com
Key JSF Concepts
* Renderer
* RenderKit
– Library of Renderers
– Extensible at runtime
– Basic HTML RenderKit is part of the specification
ramana@adityahrudayam.com
Introduction
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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:
ramana@adityahrudayam.com
RichFaces
• RichFaces is a rich component library for JSF and an
advanced framework for easily integrating AJAX
capabilities into business application development.
ramana@adityahrudayam.com
MobileFaces
• MobileFaces is a core library to extend JSF
web application to mobile devices.
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
ramana@adityahrudayam.com
ramana@adityahrudayam.com
MobileFaces
ramana@adityahrudayam.com
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)
ramana@adityahrudayam.com
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)
ramana@adityahrudayam.com
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 :
ramana@adityahrudayam.com
Ajax4JSF
Java Server Faces provided a Component Based
Architecture for building User Interface
Components for the Web Application.
Render Response
ramana@adityahrudayam.com
ramana@adityahrudayam.com
(immediate)
ValueChangeEvent
(immediate) ValueChangeEvents
ActionEvents
Apply
Restore Request Process
View Values Validations
ActionEvents
ramana@adityahrudayam.com
Application Creation
ramana@adityahrudayam.com
Application instance
• Each JSF web application has one Application Factory
ramana@adityahrudayam.com
RenderKit instance
ramana@adityahrudayam.com
Lifecycle instance
ramana@adityahrudayam.com
FaceContext instance
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
ramana@adityahrudayam.com
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)
ramana@adityahrudayam.com
Render Response Phase
• The <f:view> tag is a JSP body tag that buffers all the rendered
output from the nested JSF components.
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
ramana@adityahrudayam.com
ramana@adityahrudayam.com
ramana@adityahrudayam.com
Replacing token with serialized state and closing </f:view>
ramana@adityahrudayam.com
Restore View Phase (Postback Request)
(Postback Request)
ramana@adityahrudayam.com
Apply Request Values Phase
ramana@adityahrudayam.com
Process Validation Phase
ramana@adityahrudayam.com
Update Mode Phase
ramana@adityahrudayam.com
Invoke Application Phase
ramana@adityahrudayam.com
Postback with Navigation
ramana@adityahrudayam.com
Render Response on postback
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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).
ramana@adityahrudayam.com
Application Instance provides access to global resources
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
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
ramana@adityahrudayam.comobjects 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
ramana@adityahrudayam.com
The base UI component classes, and their HTML subclasses. All of them
Are in the javax.faces.component package
Class Family HTML Subclasses Description
ramana@adityahrudayam.com
The base UI component classes, and their HTML subclasses. All of them
Are in the javax.faces.component package
Class Family HTML Subclasses Description
ramana@adityahrudayam.com
The base UI component classes, and their HTML subclasses. All of them
Are in the javax.faces.component package
Class Family HTML Subclasses Description
ramana@adityahrudayam.com
Accessing Managed Beans Programmatically
ramana@adityahrudayam.com
Programatically accessing userid
currentBinding.setValue(context, “NewUserID”);
ramana@adityahrudayam.com
The entire UserBean instance can be retrieved by using the
Expression #{userBean} without any properties
(OR)
ramana@adityahrudayam.com
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();
}
ramana@adityahrudayam.com
Using JSF Tag Libraries
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
Types of Core Tags
•Facet tag
•Localization tag
•Container tag
•Validator tags
ramana@adityahrudayam.com
•Output tag
Event Handling Tags and Attributes
<f:phaseListener>
– Registers a PhaseListener instance on a
UIViewRoot component
ramana@adityahrudayam.com
Example: actionListener attribute in
chooseLocale.jsp
ramana@adityahrudayam.com
Example: <f:valueChangeListener>
carstore is a pacakge
ramana@adityahrudayam.com
Attribute Configuration Tag
<f:attribute>
– Adds configurable attributes (key/value pairs) to a
parent components
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
Container Tag
<f:subview>
Output Tags
<f:verbatim>
– Generates a UIOutput component that gets its
content from the body of this tag
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
<f:view> element
<f:view>
... other faces tags, possibly mixed with other
content ...
</f:view>
ramana@adityahrudayam.com
Nested View's
<f:subview>
jsp:include page="theNestedPage.jsp"
<f:subview>
ramana@adityahrudayam.com
Using HTML Tags
ramana@adityahrudayam.com
HTML Tags
* Common attributes
– id: uniquely identifies the component
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
UICommand & <h:commandButton>
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
Example1: buyCurrentCar() method of CarStore.java
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
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!
ramana@adityahrudayam.com
<h:commandButton>
<h:commandButton id="Custom“
value="#{bundle.Custom}"
styleClass="#{carstore.customizers.Custom.buttonStyle}"
actionListener="#{carstore.choosePackage}" />
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
UIInput & UIOutput Components
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
<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> ramana@adityahrudayam.com
Managed beans
• Usually represent the model or the user’s
session
• Instantiated and populated by JSF
• Different scopes
– Request
– Session
– Application
ramana@adityahrudayam.com
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)
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
Validation Methods
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
Example:
chooseLocaleFromLink()
• public void chooseLocaleFromLink(ActionEvent
event) {
String current = event.getComponent().getId();
FacesContext context =
FacesContext.getCurrentInstance();
context.getViewRoot().
setLocale((Locale) locales.get(current));
resetMaps();
}
ramana@adityahrudayam.com
Action Handler (Navigation Handler) Method
ramana@adityahrudayam.com
How to reference bean methods in Custom Tags?
<h:inputText ...validator="#{CarBean.validateInput}"
valueChangeListener="#{CarBean.processValueChange}" />
ramana@adityahrudayam.com
Types of Binding
ramana@adityahrudayam.com
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)
ramana@adityahrudayam.com
• Calling page
<h:outputText value="#{CarBean.carName}" />
ramana@adityahrudayam.com
Reasons for Binding a Component Value to
a Bean Property
ramana@adityahrudayam.com
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;
}
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
Managed Bean vs Backing Bean
ramana@adityahrudayam.com
Managed Bean vs. Backing Bean
ramana@adityahrudayam.com
Managed Bean vs. Backing Bean
<h:inputText
binding="#{BackingBean.someUICommandInstance}
" ... />
ramana@adityahrudayam.com
Managed Bean vs. Backing Bean
<h:inputText
binding="#{BackingBean.someUICommandInstance}
" ... />
ramana@adityahrudayam.com
Navigating between Pages
ramana@adityahrudayam.com
What is Navigation Model?
ramana@adityahrudayam.com
How Does It Work?
ramana@adityahrudayam.com
3.The ActionListener retrieves an outcome--
such as "success" or "failure"--from the
component generating the event
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
<navigation-rule> Element
* <from-view-id>/cars/*</from-view-id>
ramana@adityahrudayam.com
<navigation-case> Element and its Child Elements
ramana@adityahrudayam.com
Redirection
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
Navigation
• Static
– <h:commandButton
action=“display”/>
• Dynamic
– <h:commandButton
action=“#{user.doSomething}”/>
ramana@adityahrudayam.com
JSF expressions
• Invoke the property getter or setter of a
managed bean attribute
– value=“#{managedBeanName.propertyName}”
ramana@adityahrudayam.com
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)
ramana@adityahrudayam.com
JSF expressions
• Examples
– ${10+3/2}
– ${10 >= 12}
– ${user.age >= 18)
– ${!(empty user.username)}
– ${(user.name == “toto”) ? “Toto” :
“Someone else”}
ramana@adityahrudayam.com
Component Tree
• Created at Restore and View phase
• Access to each page components
• Component dynamic creation
• Access to each components in model
ramana@adityahrudayam.com
Component Tree
ramana@adityahrudayam.com
Component Tree
HtmlForm
<h:form>
HtmlInputText HtmlCommandButton
<h:inputText> <h:commandButton>
ramana@adityahrudayam.com
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”);
ramana@adityahrudayam.com
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(...);
ramana@adityahrudayam.com
Component Tree
ramana@adityahrudayam.com
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);
...
}
ramana@adityahrudayam.com
Component Tree
public void addComponent(ActionEvent actionEvent)
{
Application application = FacesContext.getCurrentInstance()
.getApplication();
ramana@adityahrudayam.com
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
–…
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
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’
ramana@adityahrudayam.com
Standard validation - usage
• To use a standard validator:
<h:inputText value=“#{user.weight}”>
<f:validateLongRange minimum=“10” maximum=“300”/>
</h:inputText>
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
Events
• Each listener can change the lifecycle by
– Calling FacesContext.renderResponse()
– Calling
FacesContext.responseComplete()
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
Components
• Fast development
• Available on the web open source or not
– MyFaces: Tomahawk
• Calendar
• Tree view
• Tabbed panel
• File upload
• …
–…
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
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; }
ramana@adityahrudayam.com
Custom component – UI class
public class UIMyTag extends UIComponentBase
{
public void encoding(FacesContext context) throws IOException {
String text = (String)getAttributes().get(“text”);
ramana@adityahrudayam.com
Facelets
ramana@adityahrudayam.com
JSF and JSP
ramana@adityahrudayam.com
JSF and JSP (Advantages)
ramana@adityahrudayam.com
JSF and JSP (Disadvantages)
ramana@adityahrudayam.com
JSF & JSP
JSF 1.1 - Initial request (e.g. index.jsf)
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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">
ramana@adityahrudayam.com
Facelets Installation
• Add jsf-facelets.jar to the classpath
• Add viewhandler config to faces-config.xml
• Change javax.faces.DEFAULT_SUFFIX to.xhtml
ramana@adityahrudayam.com
*.taglib.xml
ramana@adityahrudayam.com
Jsfc
• Jsfc : jwcid concept in Tapestry
<h:commandButton id=“btn_save” value=“Save”
action=“#{bean.method}” />
ramana@adityahrudayam.com
Inline Text
• Inline Text: Display texts without a UIComponent
<h:outputText
value=“#{IndexPageBean.welcomeMessage}” />
<h1>#{IndexPageBean.welcomeMessage}</h1>
ramana@adityahrudayam.com
Support for Unified EL
ramana@adityahrudayam.com
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}"/>
ramana@adityahrudayam.com
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)}
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
List of built-in Facelets tags
<ui:composition/>
<ui:decorate/>
<ui:define/>
<ui:include/>
<ui:insert/>
<ui:param/>
ramana@adityahrudayam.com
List of built-in Facelets tags
<ui:component/>
<ui:debug hotkey="p" rendered="true"/>
<ui:fragment/>
<ui:remove/>
<ui:repeat/>
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
TagHandlers vs Components
ramana@adityahrudayam.com
My c:if always evaluates to false
ramana@adityahrudayam.com
Solution: replace the c:if with:
ramana@adityahrudayam.com
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. ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
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 included.ramana@adityahrudayam.com
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. ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
uii:componsition vs ui:decorate
ramana@adityahrudayam.com
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()
ramana@adityahrudayam.com
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 :
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
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().
ramana@adityahrudayam.com
Creating Composition Components
<custom:inputTextLabeled
label="Name"
value="#{bird.name}" />
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
web.xml
<context-param>
<param-name>facelets.LIBRARIES</param-name>
<param-value>
/WEB-INF/facelets/mycustom.taglib.xml
</param-value>
</context-param>
ramana@adityahrudayam.com
<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> ramana@adityahrudayam.com
</html>
Facelets - Summary
• Facelets saves JSF from the burden of jsp
ramana@adityahrudayam.com
Ajax4Jsf
ramana@adityahrudayam.com
What is Ajax?
•Intuitive and natural user interaction
> No clicking required
Mouse movement is a sufficient event trigger
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
ramana@adityahrudayam.com
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
XMLHttpRequest
• JavaScript object
ramana@adityahrudayam.com
ramana@adityahrudayam.com
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
1. A Client event occurs
ramana@adityahrudayam.com
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);
}
ramana@adityahrudayam.com
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);
}
ramana@adityahrudayam.com
5. The ValidateServlet returns an XML document containing the results
(Server)
ramana@adityahrudayam.com
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 = ...;
...
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
<%@ 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>
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
a4j:poll: Bean
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
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)
ramana@adityahrudayam.com
a4j:support: Bean
ramana@adityahrudayam.com
a4j:support: Bean (Continued)
ramana@adityahrudayam.com
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/
ramana@adityahrudayam.com
Tools and Toolkits (Continued)
• Ajax4jsf
– http://labs.jboss.com/jbossajax4jsf/
• IceFaces
– http://www.icefaces.org/
ramana@adityahrudayam.com
Apache Shale
ramana@adityahrudayam.com
JSF and Other JSF and Other Frameworks
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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)
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
View Controller
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
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>
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
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
ramana@adityahrudayam.com
JBoss Seam
ramana@adityahrudayam.com
ramana@adityahrudayam.com
ramana@adityahrudayam.com
JSF Design Patterns
ramana@adityahrudayam.com
Singleton pattern
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com
Template Pattern
• If the PhaseId is ANY_PHASE, the JSF
implementation calls the PhaseListener before
and after every phase.
ramana@adityahrudayam.com
Observer Pattern
• The intent of the Observer pattern is to notify all dependent objects
(or observers) automatically when the state in the subject changes.
ramana@adityahrudayam.com
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.
ramana@adityahrudayam.com