Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
207 views

JavaServerFacesForApplicationDeveloper Readonly

Uploaded by

sahu_vibha
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
207 views

JavaServerFacesForApplicationDeveloper Readonly

Uploaded by

sahu_vibha
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 322

Java Server Faces for

application developers
(JSR 127, 252 & 314)

K.V. Ramana Rao


ramana@adityahrudayam.com

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.

JSF tackles the following challenges associated with these applications:

* Managing UI component state across requests


* Supporting encapsulation of the differences in markup across
different browsers and clients
* Supporting form processing (multi-page, more than one per
page, and so on)
* Providing a strongly typed event model that allows the application
to write server-side handlers (independent of HTTP) for client
generated events
* Validating request data and providing appropriate error reporting
* Enabling type conversion when migrating markup values (Strings)
to and from application data objects (which are often not Strings)
* Handling error and exceptions, and reporting errors in human-
readable form back to the application user
* Handling page-to-page navigation in response to UI events and
model interactions.

ramana@adityahrudayam.com
Evolution of Web aplication’s
Design Architecture

ramana@adityahrudayam.com
Evolution of MVC Architecture

1.No MVC

2.MVC Model 1 (Page-centric)

3.MVC Model 2 (Servlet-centric)

4.Web application frameworks


Struts

5.Standard-based Web application framework


JavaServer Faces (JSR-127)

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)?

* What if you want to present different JSP


pages depending on the data you receive?
– JSP technology alone even with JavaBeans and
custom tags (Model 1) cannot handle it well

* 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

Struts has been around for a few years


and has the edge on 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.

• JSF decouples the render phase from the


controller allowing developers to provide
their own render toolkits for building
custom components.
ramana@adityahrudayam.com
Struts1.x MVC
ramana@adityahrudayam.com
ramana@adityahrudayam.com
JSF MVC
ramana@adityahrudayam.com
RichFaces Architecture

ramana@adityahrudayam.com
JavaServer™ Faces (JSF) Framework Is…

“ A server side user interface (UI) component framework for


Java technology-based web applications. Drag-and-drop UI
components to build a web Application.”

ramana@adityahrudayam.com
• Environment free development
– Servlet
– Portlet
• Rendering free
– Usually HTML
– Could be not web related

ramana@adityahrudayam.com
What is JSF?

* Next generation Web application framework


based on component model
– UI Components
– Events-based interaction model
– Back-end-data integration

* Designed to be leveraged by tools (as


opposed to be used by developers directly)
– Example: Sun Java Studio Creator
– You can still create JSF application by writing JSP
pages yourself

ramana@adityahrudayam.com
Why JSF?

* Higher abstraction for Web application development


– Event-driven programming model (as opposed to
HTTP request/response programming model)

* MVC for web applications

* Extensible Component and Rendering architecture


– Support for client device independence

* Standard

* Huge vendor and industry support

ramana@adityahrudayam.com
Why JSF? (Continued)

* Offers finer-grained separation of behavior


and presentation than JSP
– Component-specific event handling
– UI elements as stateful objects on the server

* UI-component and Web-tier concepts


without limiting you to a particular view
Technology (markup language)
– Can work with any presentation technology
including JSP
– Facelets is getting popular

ramana@adityahrudayam.com
Why JSF?

* JSP and Servlet


– No built-in UI component model
* A few words on Struts first
– Struts and JSF can be used together

* 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

* Client device / protocol neutral

* Usable with JavaServer Pages (JSP)

* Usable without JSP

* Useful in the context of HTML and today's browsers

* 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

* Extensible UI component model

* Flexible rendering model

* Event handling model

* Validation framework

* Basic page navigation support

* Internationalization

ramana@adityahrudayam.com
Key JSF Concepts

* UIComponent
– Render-independent characteristics
– Base class with standard behaviors

* Standard UIComponent Subclasses:


– UICommand, UIForm, UIGraphic, UIInput,
UIOutput, UIPanel, UISelectBoolean,
UISelectMany, UISelectOne

* FacesEvent
– Base class for request and application
events

* Validator
– Base class for standard and application
defined validators

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

* Syntax similar to the expression language


of the JSP Standard Tag Library (JSTL) 1.x

* Primary interface between components and


the data provided by (or to) the application

ramana@adityahrudayam.com
Key JSF Concepts

* Renderer

– Converts components to and from a


specific markup language
– Supports render-dependent attributes on
components
– May support more than one component type

* RenderKit

– Library of Renderers
– Extensible at runtime
– Basic HTML RenderKit is part of the specification

ramana@adityahrudayam.com
Introduction

• Rapid user interface development


– Bean population
– Form validation
– Automatic conversion
– Easy localization
• Removes plumbing of JSP
• Reusable UI components
• Event driven model
• Additional components made by third-party
developers
ramana@adityahrudayam.com
Introduction
• Follows a specification
– JSF 1.1 (JSR127)
• Final Release 2: May, 27th 2004
• Requires JSP 1.2 and Servlet API 2.3
– JSF 1.2 (JSR252)
• Public Review: April 14th 2005
• Approved by the executive committee for SE/EE
• Requires JSP 2.1 and Servlet API 2.4
• Two major implementations
– Sun RI
• Available version of JSF 1.1
• CVS version of JSF 1.2
– Apache MyFaces
• Focused on JSF 1.1
• More components

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.

• In addition to custom components not found in the JSF


specification, the MyFaces components bundle also
includes an "extended" version of some of the default
components. These are basically components that exist in
either the core or html tag libraries but additional
functionality has been addded that goes beyond the
specification.

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:

• Partial-page rendering support for the entire


component set
• Integrated client-side validation

• A dialog framework

• pageFlowScope, for communicating between pages

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.

• Over 100+ AJAX-enabled components


• Extensive data visualization component set
• JSF 1.2 Support
• Complete JavaScript API
• Drag and Drop Framework
• Dialog and Popup Framework
• Navigation Menu Framework
• Built-in Internationalization and Accessiblity support

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:

• Optimized to fully leverage ICEfaces Direct-to-Dom


rendering technology providing seamless incremental
user-interface updates for all components without full-
page refreshes (partial-page rendering).

• Support for additional attributes for ICEfaces-specific


features such as effects, partialSubmit,
renderedOnUserRole, etc.

• Support for comprehensive component styling via


predefined component style sheets that are easily
customized
ramana@adityahrudayam.com
ICEfaces
• Using the ICEfaces Component Suite complete JSF applications
may be rapidly developed that fully leverage the rich
application features that ICEfaces provides:
• Smooth, incremental page updates without full-page refreshes.

• Asynchronous server-initiated user-interface updates without


polling.

• Rich AJAX-enabled web applications with no JavaScript


development required.

• User context preservation during page update, including


scrollbar positioning and user focus.

• Fine-grained user interaction during form entry that augments


the standard submit/response loop.

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.

• The RichFaces components come ready to use out-of-


the-box, so developers can immediately save time in
taking advantage of component features to create Web
applications that provide greatly improved user
experience more reliably and more quickly.

• RichFaces also includes strong support for the


skinnability of JSF applications. RichFaces also takes full
advantage of the benefits of the JSF framework including
lifecycle, validation, and conversion facilities, along with
the management of static and dynamic resources.

ramana@adityahrudayam.com
MobileFaces
• MobileFaces is a core library to extend JSF
web application to mobile devices.

• MobileFaces automatically renders standard


JSF page to different end devices.

• Open architecture with source code for further


development e.g. to support more mobile
features.

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

• MobileFaces is an open structure for easy add-on


extension for standard JSF frameworks.
MobileFaces architecture

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 :

- Asynchronous JavaScript and XML (AJAX),


- Java Server Faces (JSF),
- Enterprise Java Beans (EJB3),
- Java Portlets and Business Process Management (BPM).

ramana@adityahrudayam.com
Ajax4JSF
Java Server Faces provided a Component Based
Architecture for building User Interface
Components for the Web Application.

Ajax aims in providing Faster Response to the


Client Applications by reloading only the needed
Data. Wouldn't be nice to take the advantages
of both Jsf and Ajax for developing Robust Web
Applications. Ajax4Jsf provides solution for this.

Ajax4Jsf is the integration of JSF with Ajax


(which stands for Asynchronous JavaScript and
Xml), thereby providing Ajax Support to the Jsf
UI Components.
ramana@adityahrudayam.com
ramana@adityahrudayam.com
ramana@adityahrudayam.com
Lifecycle phases
• Restore View: recreates the server-side component tree

• Apply Request Values: copies request parameters to


component submitted values

• Process Validations: converts then validates the submitted


values

• Update Model Values: copies values to the model

• Invoke Application: invokes action listeners then actions

• Render Response: saves states and loads the next view


ramana@adityahrudayam.com
Lifecycle of JSF
Response Complete Response Complete

Request Restore Apply Process Process Process


View Request Events Validation Events
Values

Render Response

Response Complete Response Complete

Response Render Process Invoke Process Update


Response Events Application Events Model
Values

Conversion Errors / Render Response

Validation or conversion errors / Render


Response

ramana@adityahrudayam.com
ramana@adityahrudayam.com
(immediate)
ValueChangeEvent

(immediate) ValueChangeEvents
ActionEvents

PhaseEvents PhaseEvents PhaseEvents PhaseEvents

Apply
Restore Request Process
View Values Validations

ActionEvents

PhaseEvents PhaseEvents PhaseEvents

Render Invoke Update


Response Application Model Values

The Processing of events throughout the request processing lifecycle


ramana@adityahrudayam.com
Web Application Start-up
Upon receiving a JSF request, the JSF implementation much launch, or
Acquire, references to several processes/services that must be available
To JSF web application running in a servlet or portlet environment.

When a JSF web application starts, four factories are instantiated :

1. ApplicationFactory : creates the Application instance.


2. LifecycleFactory : returns a LifeCycle instance for a lifecycle id.
3. RenderKitFactory : returns a RenderKit instance
4. FaesContextFactory : create an instance of FacesContext instance
used to represent contextual information
associated with the incoming request and
eventually with the response.

ramana@adityahrudayam.com
Application Creation
ramana@adityahrudayam.com
Application instance
• Each JSF web application has one Application Factory

• This factory class is responsible for creating and replacing the


Application instance that is required by all applications
utilizing JSF.

• Application instance will then serve other processes with


services supported by this instance.

• The JSF configuration file, faces-config.xml is read once


during the creation of the web application and stored in
the Application instance.

ramana@adityahrudayam.com
RenderKit instance

• The RenderKitFactory is responsible for returning a RenderKit


instance based on the RenderKit identifier for the application.

• The HTML RenderKit is identified by a string constant


RenderFactory.HTML_BASIC_RENDER_KIT.

ramana@adityahrudayam.com
Lifecycle instance

• The Lifecycle instance is in charge of invoking processing


logic to implement the required functionality for each phase
of the request-processing lifecycle.

ramana@adityahrudayam.com
FaceContext instance

• FacesContext is used to represent contextual information


associated with the incoming request and eventually
creating the response.

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

• It is used to check whether this page has been requested


earlier or if this is a new request.

• JSF lifecycle is responsible for restoring a view from the


server and client state.

• During the first request for this view, the ViewHandler.restoreView()


method will return null, since there is no stored state.

• 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.

• Subsequently, the Restore View phase will call the


ViewHandler.createView() method to create the component
hierarchy root – UIViewRoot and attach it to the FacesContext.

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.

• During this phase, the ViewHandler.renderView() method is


called to execute the JSP document.

• The renderView() method will pass the value of the viewId


property acquired from the UIViewRoot noade as a context-
relative path to the dispatch() method of the ExternalContext
associated with the request.

• The dispatch() method will forward the value of the viewId


property (ex., /login.jspx as a context-relative path) to the
Web container

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)

• Before processing and executing the JSF JSP document,


the JSP runtime first determine the content type and
character encoding to use.

• For JSF to work in harmony with the JSP lifecycle, the


<f:view> tag needs to be present.

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.

• <f:view> tag serves as a container for all other JSF components.

• <f:view> tag is responsible for creating and storing an instance


of the ResponseWriter on the FacesContext.

• The createResponseWriter() method creates a new instance of


ResponseWriter for the specified content type and character
encoding.

• The ResponseWriter is responsible for writing the generated


markup to the requesting client, in this case the <f:view>
body content buffer.

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.

• For <h:form>, an instance of HtmlForm component is


created and attached to the UIViewRoot.

• The tag then calls encodeBegin() method of the HtmlForm.

• The encodeBegin() method on the Renderer calls methods on


the ResponseWriter to write the markup for the HTML
form element -- <form method=“” action=“”>.

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.

• HtmlFormRenderer, which in turn calls the writeState() method


on the ViewHandler.

• The writeState() method passes a token to the ResponseWriter


which is added to the <f:view> body content buffer.

• The encodeEnd() method then calls methods on the


ResponseWriter to write the closing tag for the HTML form element.

ramana@adityahrudayam.com
Render Response Phase
• The </f:view> end tag calls the writeState() method on the
StateManager.

• Depending on the init parameter – STATE_SAVING_METHOD,


the StateManager stores the state in the session on the
server or delegates to the ResponseStateManager to save
state on the client replacing the token with the serialized state.

• 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 instance of Application is created by calling the getApplication() method of


ApplicationFactory. Because this instance is shared, it must be implemented in a thread-safe
manner.

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

Class or Package Where to get reference Description


Interface
Application Javax.faces. FacesContext. Provides access to
application getApplication() supported
Locales, default render kit,
And factory methods for
creating UI components,
converters, validators and
value-binding expressions.
ValueBinding Javax.faces.el Application. Represents, a value-binding
createValueBinding expression, and provides the
UIComponent. Ability to set or evaluate that
getValueBinding() expression
MethodBinding Javax.faces.el Application. Represents a method-
createMethodBinding() binding
expression, and provides the
ability to set or evaluate that
Expression.

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.

A FacesContext instance is associated with a particular request at the beginning


of request processing, by a call to the getFacesContext() method of the
FacesContextFactory instance associated with the current web application.

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

UIComponent N/A N/A The abstract base class for


all components.

UIComponetBas N/A N/A Abstract base class with


e basic implementations of
almost all UICompnents
methods.
UIColumn Column N/A A table column. Uses to
configure template columns,
for the parent UIData
component
UICommand Command HtmlCommandButton A user command
HtmlCommandLink
UIData Data HtmlDataTable Represents a data-aware
component that cycles
through rows in the
underlying data source and
exposed individual rows to
child components. Require
UIColumn components.

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

UIForm Form HtmlForm An input form; must enclose


all input components

UIGraphic Image HtmlGraphicImage Displays an image based on


its URL

UIInput Input HtmlInputHidden A component that displays


HtmlInputSecretnput its output and collects input
HtmlInputText
HtmlInputTextarea
UIMessage Message HtmlMessage Displays messages for a
specific component
UIMessages Messages HtmlMessages Displays all messages

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

UIOutput Output HtmlOutputFormat Holds a read-only and


HtmlOutputLabel displays it to the user
HtmlOutputLink
HtmlOutputText
UIParameter Parameter N/A Represents a parameter for
a parent component

UIPanel Panel HtmlPanelGrid Groups together a set of


HtmlPanelGroup child components

UISelectBoolean Chechbox HtmlSelectBoolean- Collects and displays a


Checkbox single boolean value
UISelectItem SelectItem N/A Represents a single item or
item group. Usually used
with UISelectMany or
UISelectOne

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

UISelectItems SelectItems N/A Represents multiple items


or item groups. Usually
used with UISelectMany or
UISelectOne
UISelectMany SelectMany HtmlSelectManyCheckbox Displays a set of items,
HtmlSelectManyListbox and allows the user to
HtmlSelectManyMenu select zero or more of
them
UISelectOne SelectOne HtmlSelectOneRadio Displays a set of items,
HtmlSelectOneListbox and allows the user to
HtmlSelectOneMenu select only one of them

UIViewRoot ViewRoot N/A Represents entire view,


contains all components
on the page

ramana@adityahrudayam.com
Accessing Managed Beans Programmatically

ramana@adityahrudayam.com
Programatically accessing userid

FacesContext context = FacesContext.getCurrentInstance();

ValueBinding currentBinding = context.getApplication().


createValueBinding(“#{userBean.userid)”);

String userid = (String) currentBinding.getValue(context);

To update this value

currentBinding.setValue(context, “NewUserID”);

ramana@adityahrudayam.com
The entire UserBean instance can be retrieved by using the
Expression #{userBean} without any properties

FacesContext context = FacesContext.getCurrentInstance();

ValueBinding currentBinding = context.getApplication().


createValueBinding(#{userBean});

UserBean myuserbean = (UserBean) currentBinding.getValue(context);

(OR)

FacesContext context = FacesContext.getCurrentInstance();


UserBean myuserbean =
Context.getApplication().getVariableResolver().resolveVariable(context,
“uservean”);

ramana@adityahrudayam.com
Invoking a method on a managed bean programmatically

Application application = FacesContext.getCurrentInstance().


getApplication();

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

JSP page need to declare them

<%@ taglib uri="http://java.sun.com/jsf/html/"


prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core/"
prefix="f" %>

ramana@adityahrudayam.com
Types of Core Tags

•Event handling tags

•Attribute configuration tag

•Data conversion tags

•Facet tag

•Localization tag

•Parameter substitution tag

•Tags for representing items in a list

•Container tag

•Validator tags
ramana@adityahrudayam.com
•Output tag
Event Handling Tags and Attributes

<f:actionListener> or actionListener attribute


– Registers an action listener on a component

<f:valueChangeListener> or valueChangeListener attribute


– Registers a value-change listener on a parent component

<f:phaseListener>
– Registers a PhaseListener instance on a
UIViewRoot component

ramana@adityahrudayam.com
Example: actionListener attribute in
chooseLocale.jsp

<h:commandButton id="NAmerica" action="storeFront"


value="#{bundle.english}"
actionListener="#{carstore.chooseLocaleFromLink}">
</h:commandButton>

ramana@adityahrudayam.com
Example: <f:valueChangeListener>

<h:inputText id="firstName" value="#{customer.firstName}"


required="true">
<f:valueChangeListener type="carstore.FirstNameChanged" />
</h:inputText>

carstore is a pacakge

FirstNameChanged is a class that implements


valueChangeListener interace

ramana@adityahrudayam.com
Attribute Configuration Tag

<f:attribute>
– Adds configurable attributes (key/value pairs) to a
parent components

Parameter Substitution Tag


<f:parameter>
– Substitutes parameters into a MessageFormat
instance and to add query string name/value pairs
to a URL

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>

– Contains all JavaServer Faces tags in a page that


is included in another JavaServer Faces page

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

- Represents UIViewRoot component

- All component tags on the page must be


enclosed in the view tag

<f:view>
... other faces tags, possibly mixed with other
content ...
</f:view>

-Optional locale attribute


– Overrides the Locale stored in the UIViewRoot

ramana@adityahrudayam.com
Nested View's

Use <f:subview> element in order to include a


JSF page inside another JSP page

<f:subview>
jsp:include page="theNestedPage.jsp"
<f:subview>

ramana@adityahrudayam.com
Using HTML Tags

ramana@adityahrudayam.com
HTML Tags

* Used to control display data or accept data


from the user

* Common attributes
– id: uniquely identifies the component

– value: identifies an external data source mapped


to the component's value

– binding: identifies a bean property mapped to the


component instance

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

* Encloses all of the controls that display or


collect data from the user

* Include HTML markup to layout the controls


on the page
– <h:form> tag itself does not perform any layout

ramana@adityahrudayam.com
UICommand & <h:commandButton>

* UICommand component performs an action


(submit requests) when it is activated

– No need to use onchange to force form submits


with value change events

* Most common renderers are Button and Link

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

* In either case, the logical outcome String is used


by the navigation system to determine what page

to access when the UICommand component is


activated

– actionListener:

* is a JSF EL expression that points to a bean


method that processes an ActionEvent fired by
the UICommand component
ramana@adityahrudayam.com
Example1: <h:commandButton>

<h:commandButton action="#{carstore.buyCurrentCar}"
value="#{bundle.buy}" />

*action attribute

– references a method on the CarStore backing bean


that performs some processing and returns an
outcome
– outcome is passed to the default NavigationHandler,
which matches the outcome against a set of navigation
rules defined in the application configuration file.

* value attribute
– references the localized message for the button's label
– bundle part of the expression refers to the
ResourceBundle that contains a set of localized
messages
ramana@adityahrudayam.com
Example1: <h:commandButton>

<h:commandButton action="#{carstore.buyCurrentCar}"
value="#{bundle.buy}" />

*action attribute

– references a method on the CarStore backing bean


that performs some processing and returns an
outcome
– outcome is passed to the default NavigationHandler,
which matches the outcome against a set of navigation
rules defined in the application configuration file.

* value attribute
– references the localized message for the button's label
– bundle part of the expression refers to the
ResourceBundle that contains a set of localized
messages
ramana@adityahrudayam.com
Example1: buyCurrentCar() method of CarStore.java

public class CarStore extends Object {


...
public String buyCurrentCar() {
getCurrentModel().getCurrentPrice();
return "confirmChoices";
}
...
}

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}" />

choose Package() method of CarStore.java


public class CarStore extends Object {
...
public void choosePackage(ActionEvent event) {
String packageName = event.getComponent().getId();
choosePackage(packageName);
}
public void choosePackage(String packageName) {
// Business logic processing } ... }

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

* UIInput component displays a value to a user


and allows the user to modify this data
– The most common example is a text field

* UIOutput component displays data that cannot be modified


– The most common example is a label

* Conversions can occur

*Both UIInput and UIOutput components can be rendered


in several different ways

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

set of asterisks as it is typed

* 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

<h:inputText value="#{customer.lastName}" />


ramana@adityahrudayam.com
UIPanel Component
* Is used as a layout container for its children
* Must have the number of rows Predetermined

UIIPanelComponent and Renderer Combinations

* panelGrid
– Displays a HTML table
– Used to display entire table
– Render attributes are

* columnClasses, columns, footerClass, headerClass,


panelClass, rowClasses

* panelGroup
– Groups a set of components under one parent
– Used to represent rows in the tables

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;

public void setName(String name)


{
this.name = name;
}

public String getName()


{
return name;
}

public String doSomething()


{
// Do things
return “display”;
}
}
ramana@adityahrudayam.com
Managed beans
• Defined in faces-config.xml

<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

• A validation method must accept a


FacesContext and a UIInput component
as parameters
– just like the validate method of the Validator
interface does
• Only values of UIInput components or
values of components that extend UIInput
can be validated
• A component refers to this method with its
validate attribute
ramana@adityahrudayam.com
Example: ValidateEmail() Method

public void validateEmail(FacesContext context, UIInput toValidate) {


String message = "";
String email = (String) toValidate.getValue();
if (email.indexOf('@') == -1) {
toValidate.setValid(false);
message = CoffeeBreakBean.loadErrorMessage(context,
CoffeeBreakBean.CB_RESOURCE_BUNDLE_NAME,
"EMailError");
context.addMessage(toValidate.getClientId(context),
new FacesMessage(message, ""));
} else {
toValidate.setValid(true);
} }

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

• Takes no parameters and returns an


outcome String
• Is referenced with the component's
action attribute

ramana@adityahrudayam.com
How to reference bean methods in Custom Tags?

• As values of the following attributes


– action
– actionListener
– validator
– valueChangeListener

• Value of attributes are in the form of JSF EL expression

• Only UIInput components or components that


extend UIInput can use the validator or valueChangeListener
attributes

<h:inputText ...validator="#{CarBean.validateInput}"
valueChangeListener="#{CarBean.processValueChange}" />

ramana@adityahrudayam.com
Types of Binding

• Binding a Component Value to a Property


• Binding a Component Instance to a Bean
Property
– This bean is called Backing bean
• Binding a Component Value to an Implicit
Object (System Object)

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}" />

• Bean declaration in App. Conf. File


<managed-bean>
<managed-bean-name>CarBean</managed-bean-name>
<managed-property>
<property-name>carName</property-name>
<value>Jalopy</value>
</managed-property>
...
</managed-bean>

ramana@adityahrudayam.com
Reasons for Binding a Component Value to
a Bean Property

• The page author has more control over the


component attributes.

• The backing bean has no dependencies on the


JavaServer Faces API (such as the UI component
classes), allowing for greater separation of the
presentation layer from the model layer.

• The JavaServer Faces implementation can perform


conversions on the data based on the type of the
bean property without the developer needing to
apply a converter.
ramana@adityahrudayam.com
Binding a UI Component Instance to a Bean Property

• A component instance can be bound to a bean


property using a JSF EL expression with the
binding attribute of the component's tag

• When a component instance is bound to a


backing bean property, the property holds the
component's local value.
– Conversely, when a component's value is bound to a
backing bean property, the property holds its model
value, which is updated with the local value during the
update model values phase of the life cycle.

ramana@adityahrudayam.com
Reasons for Binding a UI Component
Instance to a Bean Property

• The backing bean can programmatically


modify component attributes

• The backing bean can instantiate


components rather than let the page
author do so
ramana@adityahrudayam.com
Example

• 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}" />

• Bean class (CashierBean.java)


public class CashierBean extends AbstractBean {
protected Date shipDate;
// ---------------------------------------------------- Component Properties
protected String name = null;
protected String shippingOption = "2";
protected String[] newsletters = new String[0];
UIOutput specialOfferText = null;
UIOutput thankYou = null;
UISelectBoolean specialOffer = null;
private CreditCardConverter creditCard = null;
private String stringProperty = "This is a String property";
ramana@adityahrudayam.com
Guideline
• In most situations, you will bind a component's
value rather than its instance to a bean property.
You'll need to use a component binding only
when you need to change one of the
component's attributes dynamically

• For example, if an application renders a


component only under certain conditions, it can
set the component's rendered property
accordingly by accessing the property to which
the component is bound.
ramana@adityahrudayam.com
Binding a Component Value to an Implicit Object

• 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

Managed bean is a JavaBean registered in


the faces-config file

– These beans have properties that are bound to


the values of UIComponents
– Uses value attribute
– <h:inputText
value="#{ManagedBean,propertyName}" ... />

ramana@adityahrudayam.com
Managed Bean vs. Backing Bean

* Backing bean is a special type of managed-bean


consisting of properties that are UIComponents
– Instead of the bean properties being bound to the
UIComponent values, they are instead bound to
the UIComponents themselves

– Uses binding attribute

<h:inputText
binding="#{BackingBean.someUICommandInstance}
" ... />

ramana@adityahrudayam.com
Managed Bean vs. Backing Bean

* Backing bean is a special type of managed-bean


consisting of properties that are UIComponents
– Instead of the bean properties being bound to the
UIComponent values, they are instead bound to
the UIComponents themselves

– Uses binding attribute

<h:inputText
binding="#{BackingBean.someUICommandInstance}
" ... />

ramana@adityahrudayam.com
Navigating between Pages

ramana@adityahrudayam.com
What is Navigation Model?

* A JSF page is represented by a component


tree, called a view, which is comprised of all
of the components on a page

* To load another page, the JSF implementation


accesses a component tree identifier and stores
the tree in the FacesContext

* The navigation model determines how this


tree is selected

ramana@adityahrudayam.com
How Does It Work?

1.When one of the components is activated--


such as by a button click--an ActionEvent is
emitted

– Any components implementing ActionSource (such


as UICommand) in the tree are automatically
registered with the default ActionListener

2.If the Invoke Application phase is reached,


the default ActionListener handles this event

ramana@adityahrudayam.com
3.The ActionListener retrieves an outcome--
such as "success" or "failure"--from the
component generating the event

– The component either literally specifies an outcome


or refers to an action method with its action property

– The action method performs some processing and


returns a particular outcome string

4.After receiving the outcome string, the


ActionListener passes it to the default
NavigationHandler

5.Based on the outcome, the currently displayed page,


and the action method that was invoked, the
NavigationHandler selects the appropriate component
tree by consulting the application configuration file
(facesconfig.xml)
ramana@adityahrudayam.com
Navigation Rules Defined Navigation Rules Defined
in faces-config.xml in faces-config.xml

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

* Each <navigation-rule> element corresponds to


one component tree identifier, defined by the
optional <from-view-id> element
– Each rule defines all the possible ways to navigate
from one particular page in the application
– If there is no <from-view-id> element, the navigation
rules defined in the <navigation-rule> element apply
to all the pages in the application
– The <from-view-id> element also allows wildcard
matching patterns

* <from-view-id>/cars/*</from-view-id>

ramana@adityahrudayam.com
<navigation-case> Element and its Child Elements

* <navigation-case> element defines a set


of matching criteria
– navigation criteria are defined by optional
<from-outcome> and <from-action> elements

* <from-outcome> element defines a logical


outcome, such as "success"

* <from-action> element refers to an action


method that returns a String, which is the
logical outcome

ramana@adityahrudayam.com
Redirection

* The current request processing is terminated


and HTTP redirect is sent to the client
– The HTTP redirect response tells client which
URL to use for the next page
– The browser's URL will reflect the new page
(without the redirection, the browser's URL
displays the original URL)

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}”

• Invoke the property getter or setter of a


managed bean attribute (Map)
– value=“#{managedBeanName.mapName[‘key’]}”
– value=“#{managedBeanName.mapName.key}”

• Invoke the property getter or setter of a


managed bean attribute (List)
– value=“#{managedBeanName.listName[0]}”
ramana@adityahrudayam.com
JSF expressions
• Invoke a predefined property, some
examples:
– #{facesContext.externalContext.session.id}
– #{param.myId}
– #{header[“Accept-Encoding”]
– #{cookie[“myCookie”].value}
– #{requestScope[“myVariable”]}
– #{sessionScope[“myVariable”]}
– #{applicationScope[“myVariable”]}
– #{initParam[“myParam”]}

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

• The view is defined in a JSP file with custom tag


libraries
...
<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>
...

ramana@adityahrudayam.com
Component Tree

• The JSP tag library implementation builds the


tree
UIViewRoot
<f:view>

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

• The button triggers the addComponent()


method on the a managed bean

<h:form>
<h:commandButton
value=“Add Component”
actionListener=“#{componentBean.addComponent}”/>
</h:form>

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();

// Create a button component and customize it


UIComponent newButton = application
.createComponent(HtmlOutputText.COMPONENT_TYPE);
newButton.setValue(”New Button”);

// Bind the triggered method to a bean method


MethodBinding mb = application.
createMethodBinding("#{bean.method}");
newButton.setAction(mb);

// Retrieve the tree root
UIViewRoot root = FacesContext.getCurrentInstance().getViewRoot();

// Retrieve the formUIComponent and add the button to it
formUIComponent.add(newButton);

}

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.

<h:inputText id=“userName” required=“true”/>


<h:message for=“userName”/>

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 objectstring and stringobject
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;

public abstract String getAsString( FacesContext context,


UIComponent component,
Object 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; }

public String getComponentType() { return “com.example.myComponentRef”; }


public String getRendererType() { return null; }

protected void setProperties(UIComponent component)


{
super.setProperties(component);
component.getAttributes().put(“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”);

ResponseWriter writer = context.getResponseWriter();


writer.startElement(“b”, this);
writer.writeAttribute(“style”, “color:blue”, null);
writer.write(text);
writer.endElement(“b”);
}

public String getFamily()


{
return null;
}
}

ramana@adityahrudayam.com
Facelets

ramana@adityahrudayam.com
JSF and JSP

JSP is the default view technology


JSP tags refer to JSF components
h:commandButton =
HtmlCommandButton
Mixing them brings overhead because of two
different lifecycles

ramana@adityahrudayam.com
JSF and JSP (Advantages)

• JSP is well adopted, reduces learning


curve of JSF ( the only advantage)

ramana@adityahrudayam.com
JSF and JSP (Disadvantages)

• JSP is created to generate dynamic


output not to create component trees
• Two different lifecycles (overhead)
• Content Interweaving Issues

ramana@adityahrudayam.com
JSF & JSP
JSF 1.1 - Initial request (e.g. index.jsf)

• 1. FacesServlet gets the request and JSF lifecycle begins


• 2. restoreState returns null and a new view is created (createView)
with view id = index.jsp (jsp is the default suffix)
• 3. lifecycle jumps to renderResponse
• 4. renderView is called that dispatches index.jsp to the container
• 5. Container traverses all the tags, tags call component’s encode
methods during component tree is created
• 6. State is saved via writeState and buffered output is rendered
to the client.

JSF 1.2 - a servletwrapper is used instead of f:view to buffer the


content and component tree is created before rendering

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

<%@ taglib uri=http://java.sun.com/jsf/html prefix="h"%>


<%@ taglib uri=http://java.sun.com/jsf/core prefix="f"%>

<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

• Concept similar to tld but lightweight


• Used to define components,
converters, validators, composition
components, custom logic tags,
functions and etc.

ramana@adityahrudayam.com
Jsfc
• Jsfc : jwcid concept in Tapestry
<h:commandButton id=“btn_save” value=“Save”
action=“#{bean.method}” />

<input jsfc="h:commandButton" type="submit"


id=“btn_save" value=“Save“
action=“#{bean.method}”/>

• Provides integration with HTML editors

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

• Facelets support the Unified EL


#{BeanName.field}
same as;
${BeanName.field}

ramana@adityahrudayam.com
Templating

• A template is an xhtml with placeholders


• Placeholders are marked with ui:insert
• Fragment from Template.xhtml
<title>
<ui:insert name="title">Default Title</ui:insert>
</title>
• In order to use the template ui:composition is needed.
• Fragment from index.xhtml
• <ui:composition template="/template.xhtml">
<ui:define name="title">
Welcome to index page
</ui:define>
ramana@adityahrudayam.com
Composition Components
• Composition component is basically a template

userInfo.xhtml

<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"> <h3>Logged


as : #{user}</h3>
</ui:composition>

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

public static String length(String name) {


if( name == null )
return null;
else
return String.valueOf( name.length() ); }

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

With JSP, mixing JSF and JSTL is


problematic
• Facelets brings limited but faultless
support
<c:if>
<c:forEach>
<c:catch>
<c:set>
ramana@adityahrudayam.com
Custom logic tags

JSTL like logic tags by extending Facelets TagHandler

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

Facelets Templating Tages

<ui:composition/>
<ui:decorate/>
<ui:define/>
<ui:include/>
<ui:insert/>
<ui:param/>
ramana@adityahrudayam.com
List of built-in Facelets tags

Non-Templating Facelets Tages

<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

The most important thing to understand about the jstl


tags in Facelets is that they do not represent components
and never become a part of the component tree once the
view has been built. Rather, they are tags which are
actually responsible for building the tree in the
first place.Once they have done their job they expire.

ramana@adityahrudayam.com
My c:if always evaluates to false

<h:dataTable values="${numbers}" var="number">


<h:column>
<c:if test="${number > 5}">
<h:outputText value="${number}"/>
</c:if>
</h:column>
</h:datatable>

Yes, the c:if is always evaluating to false! But


it is only ever evaluated once - when the tree is
built. The h:outputText component never makes it
into the tree.

ramana@adityahrudayam.com
Solution: replace the c:if with:

<ui:fragment rendered="${number > 5}"> ... </ui:fragment>

My ui:include fails inside ui:repeat

<ui:repeat value="#{bean.items}" var="item">


<ui:include src="#{item.src}"/>
</ui:repeat>

The EL for the ui:include is evaluated when the


view is built and is invalid since it relies on
a variable only made available by the ui:repeat
during rendering. Use c:forEach in this case.

ramana@adityahrudayam.com
ui:composition :The UI Composition tag is a templating tag that wraps content
to be included in another Facelet.

Any content outside of the UI Composition tag will be ignored by the


Facelets view handler.

Any content inside of the UI Composition tag will be included when


another Facelets page includes the page containing this
UI Composition tag.

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

<p><strong>composition.jsf</strong></p> <pre id="line1">


<h2>Hello World!</h2>

Tag Attributes

template String : The pathramana@adityahrudayam.com


to the template to be populated by the content within the
composition tag.
ui:debug
The UI Debug tag allows you to display helpful information about the
JSF component tree and scoped variables in your browser when you test
your JSF pages. The hotkey attribute specifies a key combination
(CTRL + SHIFT + D is the default value) to display the popup window
containing the information. The UI Debug tag can be enabled or
disabled by setting the rendered attribute.

Example:

<h:commandButton value="Continue Shopping"


action="#{shoppingCartBean.saveCart}">
<ui:debug />
</h:commandButton>

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

A value-binding expression that evaluates to a Boolean condition


ramana@adityahrudayam.com
indicating if this component should be rendered.
ui:decorate
The UI Decorate tag is a templating tag that decorates content
included from another Facelet. Any content outside of the UI
Decorate tag will be displayed by the Facelets view handler.

Any content within the decorate tag will be passed to the


associated template as parameters or simply ignored. You can use
nested ui:define tags to pass named content to the associated
template. See ui:insert for more information.

<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:

This text will be ignored.


<ui:component binding="#{myBean.component}">
<div>Hello World!</div>
</ui:component>
This text will be ignored.HTML Output

<div>Hello World!</div>

Tag Attributes

binding String

The value-binding expression linking this component tag


ramana@adityahrudayam.com
to a backing bean property.
ui:fragment

The UI Fragment tag inserts a new UIComponent instance into the


JSF
component tree. Any components or content fragments outside this
tag
will be included by the Facelets view handler. Any components or
content fragments within this tag will be added to the component
tree as children of this component instance. See also ui:component.

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:

This text will be displayed.


<ui:remove>
This text will be removed.
</ui:remove>
This text will be displayed.HTML Output

This text will be displayed. ramana@adityahrudayam.com


This text will be displayed.
ui:repeat

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

<ui:composition> will not render surrounding text, so it is a good


candidate for instantiating a 'full' page template. All of the
surrounding tags in the XHTML file doing the composition will
be replaced by the template.

Use <ui:composition> when you want to replace the entire


page with the template.

<ui:decorate> will include the expanded template into the


document at the location of the ui:decorate tag, so it can be
used inside the <ui:define> sections in the main composition.

Use <ui:decorate> for nested templates or places where


you want to include a template.

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 :

- Populates it with UIComponent children as defined in the view


description technology.
- Renders the newly constructed view to the client.

2. For Facelets, the default ViewHandler has been replaced with an


instance of the FaceletViewHandler, to fulfill the first requirement
of the renderView() method the protected buildView() method is
called. All of the Facelets-specific processing is done inside this
method and its helpers.

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.

4. The Compiler turns the collection of XHTML files that make


up the view into a tree of Facelet instances.

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().

7. When buildView() returns, the UIViewRoot has been fully


populated with the child components for the view, templates and
all.

8. Once the view has been constructed, the FaceletViewHandler


does exactly same as default ViewHandler, it renders the view
using the standard methods provided by the Faces API.

ramana@adityahrudayam.com
Creating Composition Components

Facelets provides a simple and fast way to create reusable components


using tag source files, which will define the components and fragments that
will compose our new component.

Creating the inputTextLabeled Custom Component

The first demonstration component we are going to create is a combined


h:outputLabel and h:inputText component, which we are going to call
inputTextLabeled. As combining this functionality is really common in
our applications, writing such a component will help us reuse code and
simplify our pages.

We want the component to be used like this in the JSF documents:

<custom:inputTextLabeled
label="Name"
value="#{bird.name}" />

ramana@adityahrudayam.com
InputTextLabeled.xhtml

<!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"
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>

We have created an h:outputLabelcomponent with a nested


h:inputText, which is one of the ways to use these two
ramana@adityahrudayam.com
components together
mycustom.taglib.xml

<!DOCTYPE facelet-taglib PUBLIC


"-//Sun Microsystems, Inc.//DTD
Facelet Taglib 1.0//EN"
"http://java.sun.com/dtd/
facelet-taglib_1_0.dtd">

<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

• Great for templating and composition


components plus bonuses like el
functions
• IDE support is not wide, only Exadel
support facelets for now

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

• "Partial screen update" replaces the "click, wait, and


refresh" user interaction model
> Only user interface elements that contain new information are
updated (fast response)
> The rest of the user interface remains displayed without
interruption (no loss of operational context)

• Data-driven (as opposed to page-driven)


> UI is handled in the client while the server provides data

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

• Adopted by modern browsers


> Mozilla™, Firefox, Safari, and Opera

• Communicates with a server via standard HTTP


GET/POST

• XMLHttpRequest object works in the background


for performing asynchronous communication
with the backend server
> Does not interrupt user operation
ramana@adityahrudayam.com
Server-Side AJAX Request
Processing
• Server programming model remains the same
> It receives standard HTTP GETs/POSTs
> Can use Servlet, JSP, JSF, ...
• With minor constraints
> More frequent and finer-grained requests from
client
> Response content type can be
> text/xml
> text/plain
> text/json
> text/javascript

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

• A JavaScript function is called as the result


of an event
• Example: validateUserId() JavaScript function is
mapped as a event handler to a onkeyup event on
input form field whose id is set to “userid”
<input type="text"
size="20"
id="userid"
name="id"
onkeyup="validateUserId();">
ramana@adityahrudayam.com
2. An XMLHttpRequest object is created
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;
if (!target) target = document.getElementById("userid");
var url = "validate?id=" + escape(target.value);
req.open("GET", url, true);
req.send(null);
}

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);
}

• URL is set to validate?id=greg

ramana@adityahrudayam.com
5. The ValidateServlet returns an XML document containing the results
(Server)

public void doGet(HttpServletRequest request,


HttpServletResponseresponse)
throws IOException, ServletException {
String targetId = request.getParameter("id");
if ((targetId != null) && !accounts.containsKey(targetId.trim())) {
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("<valid>true</valid>");
} else {
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("<valid>false</valid>");
}
}

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:commandButton and a4j:commandLink


– Run code on the server, then update specified JSF
element (or comma separated element list) after.
• <a4j:commandButton action="#{bean.method}"
value="Button label" reRender="some-id"/>
... <h:outputText value="#{bean.prop}" id="some-id"/>

• 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

public class TimeBean {


public Date getTime() {
return(new Date());
}
}

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

public class LocationBean implements Serializable {


private String state;
private String city;
private boolean isCityListDisabled = true;
public String getState() { return (state); }
public void setState(String state) {
this.state = state;
isCityListDisabled = false;
}
public String getCity() { return(city); }
public void setCity(String city) { this.city = city; }
public boolean isCityListDisabled() {
return(isCityListDisabled);
}

Make city list disabled initially.

ramana@adityahrudayam.com
a4j:support: Bean (Continued)

public SelectItem[] getCities() {


SelectItem[] cities =
{ new SelectItem("--- Choose City ---")};
if(!isCityListDisabled && (state != null)) {
for(StateInfo stateData:
StateInfo.getNearbyStates()) {
if(state.equals(stateData.getStateName())) {
cities = stateData.getCities();
break;
}
}
}
return(cities);
}

ramana@adityahrudayam.com
Tools and Toolkits

• Client-Side Tools
– Dojo.
• Open source JavaScript toolkit with Ajax support
• http://www.dojotoolkit.org/

– Google Web Toolkit


• Write code in Java, translate it to JavaScript
• http://code.google.com/webtoolkit/

– script.aculo.us
• Free JavaScript toolkit with Ajax support
• http://script.aculo.us/

– Yahoo User Interface Library (YUI)


• Free JavaScript toolkit with some Ajax support
• http://developer.yahoo.com/yui/

ramana@adityahrudayam.com
Tools and Toolkits (Continued)

• Hybrid Client/Server Tools


– AjaxTags (built on top of script.aculo.us)

• JSP custom tags that generate Ajax functionality


– Supports many powerful Ajax capabilities with very simple syntax
– http://ajaxtags.sourceforge.net

– JavaServer Faces (JSF) component libraries


• Trinidad (formerly Oracle ADF)
– http://www.oracle.com/technology/products/jdev/htdocs/

partners/addins/exchange/jsf/ (also myfaces.apache.org)


• Tomahawk
– http://myfaces.apache.org/tomahawk/

• 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

• JSF came into being in a world filled with frameworks


• Desire to leverage new and old capabilities together
• Two fundamental approaches to integration:
• Treat JSF as a view tier only
• Treat JSF as a controller and a view tier
• The first approach is available for several
frameworks now:
- Spring
- Struts
- Beehive
And is easily added to others
ramana@adityahrudayam.com
JSF and Other JSF and Other Frameworks

• This first approach has overlapping sets of issues:


• Resulting application architecture:
• Typically a front controller “in front of” a front controller
• JSF handles UI events, delegates form submit events
• Overall architectural elegance:
• Redundant functionality – conversion, validation, page
navigation, invoking actions
• Impedance mismatches – expression language syntax,
lifecycle differences
• Treating JSF as view tier only is recommended
primarily as a migration strategy, not as an
endgame
ramana@adityahrudayam.com
Building a framework on top of
JSF has advantages:
• Smaller – skip implementing redundant functionality
• Easier to use – learn one approach to each need
• Enables a focus on adding features and improving
ease of use
• Started work on Shale in Fall 2005, focused on:
• Adding ease of use APIs inspired by Java Studio Creator
• Integrate functionality that existing Struts users expect:
• Client side validation, Tiles layout management
• Integrate new functionality enabled by JSF
• (Later) Add a layer that leverages Java SE 5 annotations

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

• Shale provides an optional interface for your


backing bean
• Also use a naming convention for managed bean names
• Implements the “Hollywood Principle”:
• Don't call us, we'll call you
• Four application oriented callbacks are provided:
• init() -- called when view is created or restored
• preprocess() -- called when about to process a
postback
• prerender() -- called when about to render this view
• destroy() -- called after rendering, if init() was called
• AbstractViewController – Convenience base class

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

• The intent of the Singleton pattern is to ensure


that only one instance of a class is loaded, and
that the instance provides a global point of
access.
• While starting a Web application that has JSF
support, the Web container initializes a
FacesServlet instance.
• In this stage, FacesServlet instantiates the
Application and LifeCycle instances once per
Web application. These instances represent the
well-known Singleton pattern, which typically
requires only one instance of the type.
ramana@adityahrudayam.com
Singleton
• A Web application using JSF requires only one instance of the
Application and LifeCycle classes.

• LifeCycle manages the entire life cycle of multiple JSF requests.

• It makes sense to have these objects as Singleton patterns


because their states and behaviors are shared across all
requests.

• LifeCycle maintains PhaseListeners, which are also Singleton


patterns. PhaseListeners are shared by all JSF requests.

• You can use a Singleton pattern extensively in JSF framework to


reduce the memory footprint and provide global access to
objects. NavigationHandler (used to determine logical outcome
of the request) and ViewHandler (used to create view) also
represent Singleton patterns.

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.

• UIComponentBase represents an abstract Component class in the


Composite pattern. UIViewRoot is the Composite class, and
UIOutput, for example, is the leaf (or primitive).

• The UIComponentBase class defines common methods for leaf


and composite objects, such as encoding and decoding values and
child management functions. Child management functions, such as
getChildren, return an empty list for leaf nodes and children for
composite nodes.
ramana@adityahrudayam.com
Decorator Pattern
• The intent of the Decorator pattern is to extend the
behavior of an object dynamically without subclassing.
The JSF framework has many extension points, or
pluggability mechanisms.

• JSF implementation can replace default


PropertyResolver, VariableResolver, ActionListener,
NavigationHandler, ViewHandler, or StateManager by
using the Decorator pattern.

• Typically custom implementation receives the reference


to the default implementation passed through its
constructor. Custom implementation overrides only a
subset of the functionality and delegates the rest of the
functions to the default implementation.
ramana@adityahrudayam.com
Strategy Pattern
• The purpose of the Strategy pattern is to encapsulate a
concept that varies. The JSF framework employs the
Strategy pattern for rendering UI components using the
delegated implementation model.
• JSF technology supports two kinds of rendering models.
In a direct implementation model,
• UI components decode the values from the incoming
request themselves and encode the values to be
displayed.
• Delegated implementation model, decoding and
encoding operations are delegated to the separate
renderer associated with the component.

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.

• JSF implementation might register additional renderers


with the existing renderkit instance, and, at application
startup time, JSF implementation reads the configuration
file and associates those renderers to the UI
components.

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.

• The implementation is slightly different in the


JSF framework because one can have no
PhaseListeners at all, but in the Template
Method pattern, subclasses generally redefine
variant steps that are left abstract in the parent
class

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.

• The JSF framework implements the Observer pattern in UI


components. JSF technology has two kinds of built-in events:
ActionEvent and ValueChangedEvent. ActionEvent is useful in
determining the activation of user interface components such as
buttons.

• When a user clicks on the button, the JSF implementation notifies


one or more action listeners added to the button. The button is
activated or the state of the button (subject) changes.

• All listeners (or observers) are notified of the changes of state in


subject that are added to the button. Similarly, when the value in the
input UI component changes, the JSF implementation notifies
ValueChangeListeners.

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.

• EditableValueHolder is an extension of ValueHolder that describes


additional features supported by editable components, including
ValueChangeEvents and Validators.

ramana@adityahrudayam.com

You might also like