You are on page 1of 100

Java Server Faces

Welcome to Java Server Faces

23rd – 24th October 2006
DAICT Gandhinagar, India

Kedar Hukeri

23/10/2006 Kedar Hukeri

Getting Started…
 What are your expectations
 Prerequisite - Understanding the language fundamentals
and Core API of Java 2 standard edition.
- Understanding of JSP and Servlet API
 Course objectives
 Infrastructure overview
 Your feedback is very important
 Class Etiquette
 Cell phones in silence mode please
 No Internet browsing during class
Course Objective
 Understand the Java Server Faces (JSF)

 Understand MVC design Pattern

 Understand JSF lifecycle.

 Understand faces-config.xml

 Understand how to configure JSF application

 Understand JSF technology benefits

Course Agenda
1. Introduction to JSF (java server faces)

2. JSF Technology Benefits

3. JSF Design Goals

4. JSF Developer Roles

5. JSF Life Cycle

 Continued…
Course Agenda
1. Steps in the development process

2. UI component model

3. Navigation model

4. Bean management

5. How the pieces fit together

6. My first JSF application “Hello world”

 Continued…
Course Agenda
1. Advanced JSF

2. Creating custom component

3. Localization

4. Implementing event listener

5. Configuring JSF application

6. Lab exercise

Tea Break :- )
Introduction to JSF
 What is JSF - A server side user interface
component framework for Java technology-based
web applications

 A specification and reference implementation for

web application development

 Components

 Events

 Validators and Back-end-data integration

 Designed to be leveraged by tools

What is JSF
 A specification and reference implementation for
web application development framework

 Components
 Events
 Validators
 Back-end-data integration

 Designed to be leveraged by tools

 Eclipse, JBuilde, WSAD
Historical Background
 Web application programming has been a
very popular entry to J2EE programming
 Web applications can also leverage
diverse set of toolkits
 UI interface is very hard; actually harder
then they should be
 So these are fertile ground for standard
UI framework
Why JSF?...
 MVC for web applications
 Clean separation of roles
 Easy to use
 Extensible component and rendering
 Support for client device independence
Why JSF?...
 Offers finer-grained separation of behavior and
presentation then JSP
 Component-specific handling

 UI elements as stateful objects on the server

 UI-component and web-tier concepts with limiting

you to a particular scripting technology or
markup language
 Can work with any presentation technology

including JSP
Why JSF?...
 JSP and Servlet
 No built-in UI component model

 Struts
 No built-in UI component model

 No built-in event model for UI components

 No built-in state management for UI

 No built-in support of multiple renders (struts

is more or less tied up with HTML)

Not a standard (despite is popularity)
JSF is a UI Framework for
Java Web Applications



JSF Design Goals

23/10/2006 Kedar Hukeri

JavaServer Faces Must Be
 Tool friendly
 Client device/protocol neutral
 Usable with JavaServer Pages (JSP)
 Usable with out JSP
 Useful in the context of HTML and
today’s browser
 Scalable
Other Requirements
 UI components
 State Management
 Events
 Validation and error handling
 Fast performance
How the JSF specification
Fits In

Request Controller
Browser et Model

Response JSP UI
JSF Architecture

Quick overview on JSF

architecture, concept and

23/10/2006 Kedar Hukeri

Installing and Configuring JSF:
Sun Reference Implementation

 Download the JSF JAR files from

 –

 Unzip into a directory of your choice

 – E.g., on Windows, unzip into C:\Servlets+JSP , resulting in

 C:\Servlets+JSP\jsf-1_1.
 – I'll refer to this as install_dir.

 Update your class path

 – Add jsf-api.jar to the class path used by your compiler or IDE
 In the lib directory of jsf-blank or the jsf_1.1 ZIP file
JSF Architecture Server

JSF Page

Browser HTML

Front ctrl

Important Basic
 Extensible UI component model
 Flexible rendering model
 Event handling model
 Validation framework
 Basic page navigation support
 Internationalization
 Accessibility
Key JSF Concepts…
 UIComponents
 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
Key JSF Concepts…
 Converter – plug-in for String-Object conversion
 FacesContext – per-request state:
 Servlet request, response, session

 JSF request, response trees

 Model reference expression evaluators

 Syntax similar to the expression language of

the JSP Standard Tag Library (JSTL 1.0)

 Primary interface between components and

the data provided by (or to) the application

Key Concepts
 Renderer – converts components to and from a
specific markup language
 Supports render-dependent attributes on

 May support more then one component type

 RenderKit – Library of renderers

 Extensible at runtime

 Basic HTML RenderKit is part of the

Relationship to Other JSRs
 JSF is based on:
 Servlet 2.3 (JSR-53)

 JSP 1.2 (JSR-53)

 JSF must be synergistic with:

 JSTL 1.0 (JSR-52)

 Portals (JSR-168)
JSF Developer Roles

Page Author Developer
Application Implementor
Roles Definition…
 Page Author – Creates the user interface of a web
 Familiar with markup language(s) to be used

 Assembler of rebuilt components

 Use “drag and drop” IDE like Borland’s

JBuilder, WSAD, Eclipse

Roles Definition…
 Component Writer – Creates reusable
components, renderers, and libraries
 Components – render-independent properties

 Renderers – render-dependent properties

Roles Definition…
 Application Developer – creates the server-side
functionality of a web application not directly
related to the user interface
 Business logic components implemented in

standard J2EE ways

 Persistence tier components implemented in

standard J2EE ways

 Model data exposed to user interface via

JavaBean APIs
Roles Definition
 Tool Provider – creates tools to assist page
authors, component writers, and application
 GUI- oriented page development tools

 IDE to facilitate creation of components

 Application generators (from high level

Roles Definition
 Tool Provider-
 Web application frameworks that utilize JSF
components for their user interface
 JBuilder, Eclipse, WSAD

 JSF Implementer – provides runtime environment

to execute JSF webapps
Lifecycle of JSF Pages
 A JSF page is represented by a tree of UI
components, called view
 When a client makes a request for the page, the
lifecycle starts
 During the lifecycle, JSF implementation must
build the view while considering state saved from
the previous postback
Lifecycle of JSF Pages
 When the client performers a postback of the
page, JSF implementation must perform lifecycle
 Validation

 Conversion
Request Processing
Request Processing
 Life-cycle handles two types of requests
 Initial request & postback

 Initial request
 A user requests the page for the first time

 Lifecycle only executes the restore view and

render response phases

 Postback
 A user submits the form contained on a page

that was previously loaded into the browser as

a result of executing an initial request
 Lifecycle executes all phases
Request Processing
Lifecycle Phases
 Reconstitute component tree phase
 Apply request values phase
 Process validations phase
 Update model values phase
 Invoke application phase
 Render response phase
Basic Life Cycle
<HEAD> <title>Hello</title> </HEAD>
<%@ taglib uri=""
prefix="h" %>
<%@ taglib uri=""
prefix="f" %>
<body bgcolor="white">
<h:form id="helloForm" >
<h2>Hi. My name is Duke. I'm thinking of a number
value="#{UserNumberBean.minimum}"/> to
value="#{UserNumberBean.maximum}"/>. Can
you guessit?</h2>
<h:graphicImage id="waveImg" url="/"
Phase 1: Reconstitute
Component Tree (View)
 When a request for a JavaServer Faces page is
made, such as when clicking on a link or a button,
the JSF implementation begins the Restore view
 If it is the first time, an empty view is created

 JSF implementation performs

 Builds the view of the JavaServer Faces page

 Wire up event handlers and validators

 Save the view in the FacesContext

Example: Component Tree
of greeting.jsp


userNo submit errors1

Phase 2 – Apply request
values phase
 Each component in the tree extracts its new value
from the request parameters with its decode
 The value is then converted to right type then
stored locally on the components
 For userNo component in greeting.jsp page,

type gets converted from String to Integer

 Conversion errors are queued on the

Phase 3 – Process
Validation Phase
 JSF implementation processes all validations
registered on the components in the tree
 In case of validation errors
 Error messages are queued in FacesContext

 Lifecycle advances directly to the Render

Response phase
 Example
 userNo has to be between 1 and 10
Phase 4 – Update Model
Values Phase
 JSF implementation walks the component tree
and set the corresponding server side object
properties to the components’ local values
 Updated the bean properties pointed at by an

input component’s value attribute

 Type conversion from local value to model

property type
 Example in gretting.jsp
 userNumber property of the UserNumberBean

is set to the local value of the userNo

Phase 5 – Invoke
Application Phase
 JSF implementation handles any application-level
events, such as submitting a form or linking to
another page
Phase 5 – Example in
 The greeting.jsp page from the guessNumber
example has one application-level event
associated with the UICommand component
 Default ActionListener implementation retrieves
the outcome, “success”, from the component’s
action attribute
 The listener passes the outcome to the default
 The NavigationHandler matches the outcome to
the proper navigation rule defined in the
application’s application configuration file to
determine what page needs to be displayed next
 JSF implementation then sets the response view
to that of the new page
Phase 6 – Render
Response Phase
 JSF implementation invokes the components’
encoding functionality and renders the
components from the component tree saved in
the FacesContext
 Create appropriate markup from component

 If errors in previous phases, original page is

rendered with any queued error messages

 State of the response is saved so that subsequent
requests can access it and it is available to the
Restore View phase
Recap for the day
 JavaServer Faces UI components are configurable,
 elements that compose the
 user interfaces of JavaServer Faces applications.
 JavaServer Faces technology provides a rich,
flexible component architecture
 that includes the following:
 A set of UIComponent classes for specifying the
state and behavior of
 UI components
 A rendering model that defines how to render the
components in various ways
 An event and listener model that defines how to
handle component events
Introduction to JavaServer

UI Component Model

23/10/2006 Kedar Hukeri

Sub Topics
 What is a UI component?
 UI component classes
 UI component rendering model
 Conversion model
 Event and listener model
 Validation model
Introduction to JavaServer

What is a UI Component?

23/10/2006 Kedar Hukeri

What is a UI Component?
 A well defined, familiar idiom for UI design
 Are configurable, reusable elements that
compose the user interfaces of JSF applications
 Can be simple, like a button, or compound, like a
table, which can be composed of multiple
 Extensible through composition, adding new
 Accessible via JSF custom tags
JSF UI Component Model
 A set of UIComponent classes for specifying the
state and behavior of UI components
 A rendering model that defines how to render the
components in different ways
 An event and listener model that defines how to
handle component events
 A conversion model that defines how to plug in
data converters onto a component
 A validation model that defines how to register
validators onto a component
Introduction to JavaServer

UI Component Classes

23/10/2006 Kedar Hukeri

UI Component Classes…
 UI Component classes specify all of the UI
component functionality
 Holding component state

 Maintaining a reference to model objects

 Driving event-handling

 Rendering for a set of standard components

UI Component Classes
 JSF implementation provides a set of UI
component classes
 Developers can extend these UI component

classes to create custom UI components

 All JSF UI component classes extend from
 UIComponentBase defines the default state

and behavior of a UIComponent

How UI Component classes
are used by Page authors?
 Most page authors and application developers
will not have to use these classes directly
 They will instead include the components on a

page by using the component’s corresponding

 Most of these component tags can be rendered in
different ways
 For example, a UICommand can be rendered as

a button or a hyperlink
Built-in UI Component
 UICommand
 Represents a control that fires actions when

 UIForm
 Encapsulates a group of controls that submit

data to the application. This component is

analogous to the form tag in HTML
 UIGraphic
 Displays an image
Built-in UI Component
 UIInput
 Takes data input form a user

 Is a subclasses of UIOutput

 UIOutput
 Displays data output on a page

 UIPanel
 Display a table

 UIParameter
 Represents substitution parameters
Built-in UI Component
 UISelectItem
 Represents a single item in a set of items

 UISelectItems
 Represents an entire set of items

 UISelectBoolean
 Allows a user to set a boolean value on a

control by selecting or de-selecting it. This

class is a subclass of UIInput
 UISelectMany
 Allows a user to select multiple items from a

group of items. This class is a subclass of

Built-in UI Component
 UISelectOne
 Allows a user to select one item out of a group

of items. This class is a subclass of UIInput

Introduction of JavaServer

Component Rendering Model

23/10/2006 Kedar Hukeri

Component Rendering
 Rendering is handled by Render kit not by
component classes
 Component writers can define the behavior of

a component once, but create multiple

 Page authors and application developers can
change the appearance of a component on the
page by selecting the tag that represents the
appropriate component/renderer combination
 <h:command_button>

 <h:command_link>
 Defines how component classes map to
component tags appropriate for a particular
 JSF implementation includes a built-in RenderKit
for rendering to an HTML client
 For every UI component that a RenderKit
supports, the RenderKit defines a set of Renderer
Renderer Object
 Defines a different way to render the particular
component to the output defined by the
 Example
 UISelectOne component has three different

 One of them render the component as a set

of radio buttons
 Another renders the component as a combo

 The third one renders the component as a

list box
Introduction to JavaServer

JSP Custom Tags in HTML

Renderer Kit

23/10/2006 Kedar Hukeri

Tags in HTML Renderer Kit
 Each JSP custom tag defined in the standard
HTML RenderKit class is composed of
 Component functionality, defined in the

UIComponent class
 Rendering attributes, defined by the Renderer
Example Tags
 <command_button> & <command_link> tags
 “command” defines UI component

 “button” and “link” defines rendering

<h:form id="helloForm" >
<h2>Hi. My name is Duke. I'm thinking
of a number from
"/> to
"/>. Can you guess it?
<h:graphic_image id="waveImg"
Introduction to JavaServer

Conversion Model

23/10/2006 Kedar Hukeri

Conversion Model
 A component can be associated with server-side
model object data
 Two views of the component’s data
 Model view

 Presentation view

 Component’s data can be converted between the

model view and the presentation view
Introduction to JavaServer

Event & Listener Model

23/10/2006 Kedar Hukeri

JSF Events & Listener
 Similar to JavaBeans event model
 Listener and Event classes that an application

can use to handle events generated by UI

 An Event object identifies the component that

generated the event and stores information

about the event
 To be notified of an event, an application must

provide an implementation of the Listener

class and register it on the component that
generates the event
 When the user activates a component, such as

by clicking a button, an event is fired.

Introduction to JavaServer

Validation Model

23/10/2006 Kedar Hukeri

Validation Model
 Like the conversion model, the validation model
defines a set of standard classes for performing
common data validation checks
 jsf-core tag library also defines a set of tags that
correspond to the standard Validator
 Most of the tags have a set of attributes for
configuring the validator’s properties
 Minimum and maximum
<h:form id="helloForm" >
<h2>Hi. My name is Duke. I'm thinking
of a number from
"/> to
"/>. Can you guess it?
<h:graphic_image id="waveImg"
Introduction to JavaServer

Application Configuration

23/10/2006 Kedar Hukeri

Application Configuration
 XML file for configuring resources required at
application startup time
 Navigation rules, converters, validators,

render kits
 Usually names as faces-config.xml
 A <faces-config> tag must enclose all of the
other declarations
 <faces-config>
 …
 </faces-config>
Faces-config.xml of
<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD
JavaServer Faces Config 1.0//EN"
Faces-config.xml of
Application Configuration
 You can have more than one application
configuration file
 There are three ways that you can make these
files available to the application
 A resource named /META-INF/faces-config.xml

in any of the JAR files in the Web application’s

/WEB-INF/lib directory
 A context init parameter,

 A resource named faces-config.xml in the

/WEB-INF/ directory of your application (most

Application Class
 When an application starts up, the JSF
implementation creates a single instance of the
Application class
 Is automatically created for each application
 FacesConext.getApplication()
Introduction to JavaServer

Using JSF Tag Libraries

23/10/2006 Kedar Hukeri

Two Tag Libraries
 html_basic
 Defines tags for representing common HTML

user interface components

 jsf_core
 Defines other JSF related tags

 Independent of any rendering technology

 JSP page need to declare them

 <%@ taglib uri=

prefix=“h” %>
 <%@ taglib uri=

prefix=“f” %>
<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

 </f:view>
 Optional locale attribute
 Overrides the Locale stored in the UIViewRoot
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>
Introduction to JavaServer

Using Core Tags

23/10/2006 Kedar Hukeri

Event Handling Tags
 <f:action_listener>
 Register an action listener on a parent

 <f:valuechange_listener>
 Registers a value-change listener on a parent

JSF Advantages
 Custom GUI controls
 – JSF provides a set of APIs and associated custom tags to
 HTML forms that have complex interfaces
 Event handling
 – JSF makes it easy to designate Java code that is invoked
when forms
 are submitted. The code can respond to particular buttons,
 in particular values, certain user selections, and so on.
 Managed beans
 – In JSP, you can use property="*" with jsp:setProperty to
 automatically populate a bean based on request
parameters. JSF
 extends this capability and adds in several utilities, all of
 serve to greatly simplify request param processing.
JSF Advantages…
Continued 2
 Form field conversion and validation
 – JSF has built-in capabilities for checking that form values
are in the
 required format and for converting from strings to various
other data
 types. If values are missing or in an improper format, the
form can
 be automatically redisplayed with error messages and with
 previously entered values maintained.
 Centralized file-based configuration
 – Rather then hard-coding information into Java programs,
many JSF
 values are represented in XML or property files. This loose
 means that many changes can be made without modifying
JSF Advantages…
Continued 3
 Custom components
 – JSF makes it relatively easy to combine complex GUIs
 into a single manageable component; Struts does not
 Support for other display technologies
 – JSF is not limited to HTML and HTTP; Struts is
 Access to beans by name
 – JSF lets you assign names to beans, then you refer to
 them by name in the forms. Struts has a complex process
 with several levels of indirection where you have to
 remember which form is the input for which action.
 Expression language
 – The JSF expression language is more concise and
 powerful than the Struts bean:write tag.
 This is less advantageous if using JSP 2.0 anyhow.
JSF Advantages…
Continued 4
 Simpler controller and bean definitions
 – JSF does not require your controller and bean classes to
 extend any particular parent class (e.g., Action) or use
 any particular method (e.g., execute). Struts does.
 Simpler config file and overall structure
 – The faces-config.xml file is much easier to use than is the
 struts-config.xml file. In general, JSF is simpler.
 More powerful potential tool support
 – The orientation around GUI controls and their handlers
 opens possibility of simple to use, drag-and-drop IDEs
Installing and Configuring JSF:
Sun Reference Implementation

 Download the JSF JAR files from

 –

 Unzip into a directory of your choice

 – E.g., on Windows, unzip into C:\Servlets+JSP , resulting in

 C:\Servlets+JSP\jsf-1_1.
 – I'll refer to this as install_dir.

 Update your class path

 – Add jsf-api.jar to the class path used by your compiler or IDE
 In the lib directory of jsf-blank or the jsf_1.1 ZIP file
Disadvantages of JSF
 Bigger learning curve
 – To use MVC with the standard RequestDispatcher, you
 need to be comfortable with the standard JSP and servlet
 APIs. To use MVC with JSF, you have to be comfortable
 with the standard JSP and servlet APIs and a large and
 elaborate framework that is almost equal in size to the
 core system. This drawback is especially significant with
 smaller projects, near-term deadlines, and less
 experienced developers; you could spend as much time
 learning JSF as building your actual system.
Disadvantages of JSF …Continued 2
 Worse documentation
 – Compared to the standard servlet and JSP
APIs, JSF has
 fewer online resources, and many first-time users
find the
 online JSF documentation confusing and poorly
 organized. There are also few good books yet out
on JSF.
Disadvantages of JSF …Continued 3
 Established base and industry momentum
 – Struts has a large core of existing developers and momentum
 both developers and IT managers; JSF does not.
 • Support for other display technologies
 – JSF is not limited to HTML and HTTP; Struts is
 • Hey! Didn't I say this was an advantage of JSF?
 • Confusion vs. file names
 – The actual pages used in JSF end in .jsp. But the URLs used end
 .faces or .jsf. This causes many problems; in particular, in JSF
 • You cannot browse directories and click on links
 • It is hard to protect raw JSP pages from access
 • It is hard to refer to non-faces pages in faces-config.xml
Disadvantages of JSF …Continued 4
 Less current tool support

 – Struts is supported by many widely used IDEs; JSF is not

 – Struts comes with validators for email address, credit
card numbers,
 regular expressions, and more. JSF only comes with
validators for
 missing values, length of input, and numbers in a given

 But MyFaces has several powerful validators

 Lack of client-side validation

 – Struts supports JavaScript-based form-field validation;
JSF does not
Bookmark the JSF Documentation

 API Javadocs
 –
 • Same as the MyFaces version
 • Tag library docs
 –
 • Much better than the MyFaces version
 • faces-config.xml annotated DTD
 –
 • MyFaces References
 –
 • User's Guide, extensions documentation, FAQs, etc.
 JSF provides many useful features for
 Developing complex GUIs & handling events

 Standard servlet and JSP technology is a viable alternative

 – Especially when the MVC approach and the JSP 2.0
 expression language is used

 Struts is also a viable alternative

Thank You …
 Questions
 Happy Diwali and New Year
 Enjoy Programming….

 Kedar Hukeri