Programming/JSF
JavaServer Faces
Jared
2008. 6. 21. 17:05
Introduction to JSF
JavaServer Faces is a framework that simplifies development of sophisticated web application user interfaces, primarily by defining a user interface component model tied a well defined request processing life cycle.
Objectives of JSF
To provide event-driven component based technology for developoing web applications.
To separate the user interface from the model objects that encapsulate the dat and application logic.
To provde the server side validation and dat conversion.
To retain the state of the components.
Overview of JSF
JSF is a framework for buildingser interfaces for web applications.
It brings component-based model to web application development.
It focuses only onn user interface details and is not concerned about ahow the rest of the application is implemnted.
It includes:
It supports MVC architecture.
Advantages of JSF
Ease of use.
Java programmers to develop the application backend without worrying about HTTP details and integrate it with user interface through a familiar event-driven model with type-safe interfaces.
Vendors can develop powerful tools for both frontend and backend development.
Comparing JSF with JSP
JSP
Because of the extensibility and eas-of-use that JSF technology provides, a wide range of developers and web-page designers can tak advantage of the power of JSF technology. These users include:
What is a component?
JSF UI components are configurable, reusable elements that compose the use interfaces of JSF applications. A component can be simple, such as a button, or compound, such as a table, which can be composed of multiple components.
JSF technology provides a rich, flexible component architecture that includes the following:
2. Component Rendering Model
JSF component architecture is designed such that functionality of the components is defined by the component classes, whereas the component rendering can be defined by a separate renderer. This design has several benefits including:
Render classes
For every UI Component that a render kit supports, the render kit defines a set of renderer classes.
Each renderer class defines a different way to render the particular component to the output defined by the render kit.
For example a UISelectOne component has three different renderers. One of them renderes the component as a set of radio buttons. Another renders the component as a combo box. The third one renderes the component as a list box.
Each JSP custom tag defined in the standard HTML render kit is composed of the component functionality (defined in UIComponent class) and the rendering attributes (defined by the renderer class).
EXAMPLE: How rendering is done?
The two tags commandButton and commandLink that represent a UICommand component rendered in two different ways as shown below.
(image shot missed)
3. Conversion Model
A JavaServer Faces application can optionally associate a component with server-side object data. This object is a JavaBeans component, such as backing bean. An application gets and sets the object data for a component by calling the appropriate object properties for that component.
When a component is bound to an object, the application has two views of the component's data:
The JSF technology automatically converts the component data between the model view and the presentation view.
You can create your own custom converter.
To create a custom converter in your application, three things must be done:
4. Event and Listener Model
The JSF event and listener model is similar to the JavaBean event model.
An Event object identifiers the component that generated the event and stored the information about the event.
To be notified of an event, an application must provide an implementation of the Listener class and must register it on the component that generates the event.
When the user activates the component, such as by clicking a button, an event is fired. This cuases the JSF implementation to invoke the listener method that processes the event.
Types of events
5. Validataion Model
JavaServer Faces technology supports a mechanism for validating the local data of editable components (such as text fields). This validation occurs before the corresponding model data is updated to match the local value.
Like the conversion model, the validation model defines a set of standard classes for performing common data validation checks.
The JavaServer Faces core tag library also defines a set of tags that correspond to the standard Validator implementations.
Most of the tags have a set of attributes for configuring the validator's properties, such as the minimum and maximum allowable values for the component's data. The page author registers the validator on a component by nesting the validaotr's tag withing the component's tag.
Creating your own Custom Validator
The validation model also allows you to create your own custom validator and corresponding tag to perform custom validation. The validation model provides two ways to implement custom validation:
Usage of few UI components
Few important UI components are:
Using UI components
Object creationg in JSF
JSF Tag Libraries
JSF provides tag libraries needed by Java developers that build web based user interfaces.
JSF contains two tag libraries called JSF Core and HTML Basic.
The former provides a few general tags and some other tags that let you register validators and event listeners to UI components.
The latter contains JSP tags that render HTML UI components such as buttons, text fields, checkboxes, lists, etc.
Using tag libraries
The standard prefixes of these two tag libraries are f and h, and they are declared at the beginning of jsp page as follows:
The <f:faces> tag is a container tag that must enclose all other JSF tags that are used in a page. It doesn't generate any HTML content, but it triggers internal JSF mechanisms.
Steps involved in a sample application
Developing a simple JavaServer Faces application usually requires these tasks:
1. Create the pages using the UI component ans core tags.
2. Define page navigation in the application configuration resource file.
3. Develop the backing beans.
4. Add managed bean declarations to the application configuration resource file.
Directory structure
NavigationRule
index.jsp
blue.jsp
green.jsp
WEB-INF
web.xml
faces-config.xml
lib
commons-beanutils.jar
commons-collections.jar
commons.digester.jar
commons-logging.jar
jsf-api.jar
jsf-impl.jar
jstl.jar
standard.jar
Example: Displaying the name user entered.
Let us develop a simple application using JSF in which the user enters his name and password and clicks the command button. Then a new page is displayed greeting the user.
For this application we write two JSP pages index.jsp and welcome.jsp.
In index.jsp user enters his name and password.
When the user enters the command button welcome.jsp is displayed.
This does not reflect the exact purpose of JSF but gives a brief overview on how JSF can be used.
Step1: Creating JSP pages
index.jsp may look like this:
welcome.jsp may look like this:
Step2: Developing the Backing Bean
Step3: Defining Navigation rules
The following navigation rules are added to the application configuration resource file (faces-config.xml)
Step4: Defining beans
The managed beans declarations are added to the application configuration resource file (faces-config.xml)
Component Tree
UIForm - UIInput, UIInput, UICommand
JSF life cycle
(image missed)
JSF basic life cycle
(image missed)
Conversion and Validation in JSF
(image missed)
JSF versus Struts
JSF
From the differences we have seen till now it should come as no surprise that it is possibel to use JSF with an application framework like Struts.
Basically, all requests are processed by the JSF until it is clear that backend code needs to be invoked.
The control is then passed on to struts, and eventally comes back to JSF for rendering of the response.
Though there is some overlap between Struts and JSF regarding navigation and validation they are flexible enough that you can pick and which should be in charge of these tasks.
Services of JSF framework
MVC architecture
Data conversion
Validation and error handling
Internationalization
Custom components
Alternative renderers
Tool support
High level view of JSF
FAQ
What is JavaServer Faces technology?
What are the benefits of JavaServer Faces technology?
Who are the intended users of JavaServer Faces technology?
What is the difference between Struts and JSF?
How does JavaServer Faces technology relate to JavaServer Pages (JSP) technology?
JavaServer Faces is a framework that simplifies development of sophisticated web application user interfaces, primarily by defining a user interface component model tied a well defined request processing life cycle.
Objectives of JSF
To provide event-driven component based technology for developoing web applications.
To separate the user interface from the model objects that encapsulate the dat and application logic.
To provde the server side validation and dat conversion.
To retain the state of the components.
Overview of JSF
JSF is a framework for buildingser interfaces for web applications.
It brings component-based model to web application development.
It focuses only onn user interface details and is not concerned about ahow the rest of the application is implemnted.
It includes:
- A set of APIs for representing UI components and managing their state, handing evnets and input validation, page navigation, and supporting internationalization and accessibility.
- A JavaServer Pages custom tag library for expressing a JavaServer Faces interface with a JSP page.
It supports MVC architecture.
Advantages of JSF
Ease of use.
Java programmers to develop the application backend without worrying about HTTP details and integrate it with user interface through a familiar event-driven model with type-safe interfaces.
Vendors can develop powerful tools for both frontend and backend development.
Comparing JSF with JSP
JSP
- No input data validation.
- Data conversion when used with beans.
- Encapsulates application code and presentation.
- Does not provide strong tools
- Input data validation.
- Data conversion.
- Completely separates application code and presentation.
- Provides powerful tools.
Because of the extensibility and eas-of-use that JSF technology provides, a wide range of developers and web-page designers can tak advantage of the power of JSF technology. These users include:
- Page Authors: who creates the user interfaces.
- Application developers: who write the application code, including the data-access, event-handling, and business logic.
- Component writers: who construct reusable UI components, and custom components.
- Tools vendors: who build tools leveraging JavaServer Faces technology to make building a user interface with JavaServer Faces technology even easier.
What is a component?
- In JSF, a component is a group of classes that together provide a reusable piece of web-based user interface code.
- Render class.
- UIComponent subclass.
- JSP custom action class.
- As defined by the JavaServer Faces technology navigation is the set of rules for choosing the next page to be displayed after a button of hyperlink is clicked. These rules are defined by the application architect in the application configuration resource file using a small set of XML elements.
- To handle navigation in simple applications:
- Define the rules in the application configuration resource file.
- Refer to an outcome String from the button or hyperlink component's action attribute. This outcome String is used by the JavaServer Faces implementation ot select the navigation rule.
- In complicated applications we also must provide one or more action methods, which performs some processing to determine what page should be displayed next. The component that triggers navigation references this method.
- When a button or hyperlink is clicked the component associated with it generates an action event.
- This event is handled by the default ActionListener instance, which calls the action method referenced by the component that triggerted the event.
- This action method is located in backing bean and is provided by application developer.
- This action method returns a logical outcome String which describes the result of the processing.
- The listener passes the outcome and a reference to the action method that produced the outcome to the default NavigationHandler.
- The NavigationHandler selects the next page to be displayed by matching the outcome or the action method reference against the navigation rules in the application configuration resource file.
- Each navigation rule defines how to navigate from one particular page to any number of other pages in the application.
- Each navigation case within the navigation rule defines the target page and either a logical outcome, a reference to an action method, or both.
<navigation-rule>
<from-view-id>/greeting.jsp</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/response.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<from-view-id>/greeting.jsp</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/response.jsp</to-view-id>
</navigation-case>
</navigation-rule>
- The rule states that when the button or hyperlink component on greeting.jsp is activated, the application will navigate from the greeting.jsp to the response.jsp if the outcome referenced by the button or hyperlink component's tag is success.
JSF UI components are configurable, reusable elements that compose the use interfaces of JSF applications. A component can be simple, such as a button, or compound, such as a table, which can be composed of multiple components.
JSF 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.
- A conversion model that defines how to register data converters on to a component.
- A validation model that defines how to register validators on to a component.
- JSF technology provides set of UI component classes and associated behavioral interfaces that specify all the UI component functionality, such as holding component state, maintaining reference to objects, and driving event handling and rendering for a set of standard components.
- The component classes are completely extensible, allowing component writers to create their own custom components.
- All JSF UI Component classes extend UIComponentBase, which defines the default state and behavior of a UI component.
- In addition to extending the UIComponentBase, the component class also implement one of more behavioral interfaces, each of which defines certain behavior for a set of components whose classes implement the interface.
ActionSource: Indicates that the component can fire an action event.
EditableValueHolder: Extends ValueHolder and specifies additional features for editable components, such as validation and emitting value-change events.
NamingContainer: Mandates that each component rooted at this component have a unique ID.
StateHolder: Denotes that a component has state that must be saved between requests.
ValueHolder: Indicates that the component maintains a local value as well as the option accessing data in the model tier.
EditableValueHolder: Extends ValueHolder and specifies additional features for editable components, such as validation and emitting value-change events.
NamingContainer: Mandates that each component rooted at this component have a unique ID.
StateHolder: Denotes that a component has state that must be saved between requests.
ValueHolder: Indicates that the component maintains a local value as well as the option accessing data in the model tier.
2. Component Rendering Model
JSF component architecture is designed such that functionality of the components is defined by the component classes, whereas the component rendering can be defined by a separate renderer. This design has several benefits including:
- Component wirters can define the behavior of the component once but create multiple renderers, each of which defines a different way to render the component to the same client or different clients.
- Page authors and application developers can change the appearance of a component on the page by selecting the tag that represents the appropriate combination of component and renderer.
Render classes
For every UI Component that a render kit supports, the render kit defines a set of renderer classes.
Each renderer class defines a different way to render the particular component to the output defined by the render kit.
For example a UISelectOne component has three different renderers. One of them renderes the component as a set of radio buttons. Another renders the component as a combo box. The third one renderes the component as a list box.
Each JSP custom tag defined in the standard HTML render kit is composed of the component functionality (defined in UIComponent class) and the rendering attributes (defined by the renderer class).
EXAMPLE: How rendering is done?
The two tags commandButton and commandLink that represent a UICommand component rendered in two different ways as shown below.
(image shot missed)
3. Conversion Model
A JavaServer Faces application can optionally associate a component with server-side object data. This object is a JavaBeans component, such as backing bean. An application gets and sets the object data for a component by calling the appropriate object properties for that component.
When a component is bound to an object, the application has two views of the component's data:
- The model view, in which data is represented as data types, such as int or long.
- The presentation view, in which data is represented in a manner that can be read or modified by the user. For example, a java.util.Date might be represented as a text string in the fromat mm/dd/yy or as a set of three text strings.
The JSF technology automatically converts the component data between the model view and the presentation view.
You can create your own custom converter.
To create a custom converter in your application, three things must be done:
- The application developer must implement the Converter class.
- The application architect msut register the Converter with the application.
- The page author must refer to the Converter from the tag of the component whose data must be converted.
4. Event and Listener Model
The JSF event and listener model is similar to the JavaBean event model.
An Event object identifiers the component that generated the event and stored the information about the event.
To be notified of an event, an application must provide an implementation of the Listener class and must register it on the component that generates the event.
When the user activates the component, such as by clicking a button, an event is fired. This cuases the JSF implementation to invoke the listener method that processes the event.
Types of events
Value-changed event: occurs when the user changes the value of the component represented by UIInput or one of its subclass.
Action-event: occurs when the user activates a component that implements ActionSource. These actions include buttons and hyperlinks.
Data-model events: occurs when a new row of a UIData component is selected.
Action-event: occurs when the user activates a component that implements ActionSource. These actions include buttons and hyperlinks.
Data-model events: occurs when a new row of a UIData component is selected.
5. Validataion Model
JavaServer Faces technology supports a mechanism for validating the local data of editable components (such as text fields). This validation occurs before the corresponding model data is updated to match the local value.
Like the conversion model, the validation model defines a set of standard classes for performing common data validation checks.
The JavaServer Faces core tag library also defines a set of tags that correspond to the standard Validator implementations.
Most of the tags have a set of attributes for configuring the validator's properties, such as the minimum and maximum allowable values for the component's data. The page author registers the validator on a component by nesting the validaotr's tag withing the component's tag.
Creating your own Custom Validator
The validation model also allows you to create your own custom validator and corresponding tag to perform custom validation. The validation model provides two ways to implement custom validation:
Implement a Validator interface that performs the validation.
Implement a backing bean method that performs the validation.
If you are implementing a Validator interface, you must also:Implement a backing bean method that performs the validation.
Register the Validator implementation with the application.
Create a custom tag or use a validator tag to register the validator on the component.
Create a custom tag or use a validator tag to register the validator on the component.
Usage of few UI components
Few important UI components are:
UIForm: Encapsulates a group of controls that submit data to the application. This component is analogous to the form tag in HTML.
UIInput: Takes data input from a user. This class is a subclass of UIOutput.
UICommand: Represents a control that fires actions when activated.
UIOutput: Displays data output on a page.
UIMessage: Displays a localized message.
UIInput: Takes data input from a user. This class is a subclass of UIOutput.
UICommand: Represents a control that fires actions when activated.
UIOutput: Displays data output on a page.
UIMessage: Displays a localized message.
Using UI components
<h:form>
<h3>Please enter your name and password.</h3>
Name:
<h:inputText id = "name" value ="#{user.name}" required = "true" >
<f:validateLength minimum = "2" maximum = "5" />
</h:inputText>
<h:message for = "name" />
Password:
<h:inputSecret id = "password" value ="#{user.password}" required = "true"/>
<h:message for = "password" />
<h:commandButton value = "Login" action = "login"/>
</h:form>
<h3>Please enter your name and password.</h3>
Name:
<h:inputText id = "name" value ="#{user.name}" required = "true" >
<f:validateLength minimum = "2" maximum = "5" />
</h:inputText>
<h:message for = "name" />
Password:
<h:inputSecret id = "password" value ="#{user.password}" required = "true"/>
<h:message for = "password" />
<h:commandButton value = "Login" action = "login"/>
</h:form>
Object creationg in JSF
JSF Tag Libraries
JSF provides tag libraries needed by Java developers that build web based user interfaces.
JSF contains two tag libraries called JSF Core and HTML Basic.
The former provides a few general tags and some other tags that let you register validators and event listeners to UI components.
The latter contains JSP tags that render HTML UI components such as buttons, text fields, checkboxes, lists, etc.
Using tag libraries
The standard prefixes of these two tag libraries are f and h, and they are declared at the beginning of jsp page as follows:
<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
The <f:faces> tag is a container tag that must enclose all other JSF tags that are used in a page. It doesn't generate any HTML content, but it triggers internal JSF mechanisms.
Steps involved in a sample application
Developing a simple JavaServer Faces application usually requires these tasks:
1. Create the pages using the UI component ans core tags.
2. Define page navigation in the application configuration resource file.
3. Develop the backing beans.
4. Add managed bean declarations to the application configuration resource file.
Directory structure
NavigationRule
index.jsp
blue.jsp
green.jsp
WEB-INF
web.xml
faces-config.xml
lib
commons-beanutils.jar
commons-collections.jar
commons.digester.jar
commons-logging.jar
jsf-api.jar
jsf-impl.jar
jstl.jar
standard.jar
Example: Displaying the name user entered.
Let us develop a simple application using JSF in which the user enters his name and password and clicks the command button. Then a new page is displayed greeting the user.
For this application we write two JSP pages index.jsp and welcome.jsp.
In index.jsp user enters his name and password.
When the user enters the command button welcome.jsp is displayed.
This does not reflect the exact purpose of JSF but gives a brief overview on how JSF can be used.
Step1: Creating JSP pages
index.jsp may look like this:
<html>
<%@taglib uri="/WEB-INF/html_basic.tld" prefix="h"%>
<%@taglib uri="/WEB-INF/jsf_core.tld" prefix="f"%>
<f:view>
<head>
<title>A simple java server faces application</title>
</head>
<body>
<h:form>
<h3>Please enter your name and password.</h3>
<table>
<tr>
<td>Name:</td>
<td>
<h:inputText id="name" value="#{user.name}" required="true">
<f:validateLength minimum="2" maximum="5"/>
</h:inputText>
</td>
<td><h:message for="name"/></td>
</tr>
<tr>
<td>Password:</td>
<td>
<h:inputSecret id="password" value="#{user.password}" required="true"/>
</td>
<td><h:message for="password"/></td>
</tr>
</table>
<p>
<h:commonButton value="Login" action="login"/>
</p>
</h:form>
</body>
</f:view>
</html>
<%@taglib uri="/WEB-INF/html_basic.tld" prefix="h"%>
<%@taglib uri="/WEB-INF/jsf_core.tld" prefix="f"%>
<f:view>
<head>
<title>A simple java server faces application</title>
</head>
<body>
<h:form>
<h3>Please enter your name and password.</h3>
<table>
<tr>
<td>Name:</td>
<td>
<h:inputText id="name" value="#{user.name}" required="true">
<f:validateLength minimum="2" maximum="5"/>
</h:inputText>
</td>
<td><h:message for="name"/></td>
</tr>
<tr>
<td>Password:</td>
<td>
<h:inputSecret id="password" value="#{user.password}" required="true"/>
</td>
<td><h:message for="password"/></td>
</tr>
</table>
<p>
<h:commonButton value="Login" action="login"/>
</p>
</h:form>
</body>
</f:view>
</html>
welcome.jsp may look like this:
<html>
<%@taglib uri="/WEB-INF/jsf_core.tld" prefix="f"%>
<%@taglib uir="/WEB-INF/html_basic.tld" prefix="h"%>
<f:view>
<head>
<title>welcome page</title>
</head>
<body bgcolor="#ffffff">
<h3>Have a nice time,
<h:outputText value="#{user.name}"/>
</h3>
</body>
</f:view>
</html>
<%@taglib uri="/WEB-INF/jsf_core.tld" prefix="f"%>
<%@taglib uir="/WEB-INF/html_basic.tld" prefix="h"%>
<f:view>
<head>
<title>welcome page</title>
</head>
<body bgcolor="#ffffff">
<h3>Have a nice time,
<h:outputText value="#{user.name}"/>
</h3>
</body>
</f:view>
</html>
Step2: Developing the Backing Bean
public class UserBean {
private String name:
private String password;
public String getName() {
return name;
}
public void setName(String userName) {
this.name = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String userPassword) {
this.password = userPassword;
}
}
private String name:
private String password;
public String getName() {
return name;
}
public void setName(String userName) {
this.name = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String userPassword) {
this.password = userPassword;
}
}
Step3: Defining Navigation rules
The following navigation rules are added to the application configuration resource file (faces-config.xml)
<navigation-rule>
<from-view-id>/index.jsp</from-view-id>
<navigation-case>
<from-outcome>login</from-outcome>
<to-view-id>/welcome.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<from-view-id>/index.jsp</from-view-id>
<navigation-case>
<from-outcome>login</from-outcome>
<to-view-id>/welcome.jsp</to-view-id>
</navigation-case>
</navigation-rule>
Step4: Defining beans
The managed beans declarations are added to the application configuration resource file (faces-config.xml)
<managed-bean>
<managed-bean-name>user</managed-bean-name>
<managed-bean-class>UserBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<managed-bean-name>user</managed-bean-name>
<managed-bean-class>UserBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
Component Tree
UIForm - UIInput, UIInput, UICommand
JSF life cycle
(image missed)
JSF basic life cycle
(image missed)
Conversion and Validation in JSF
(image missed)
JSF versus Struts
JSF
- User interface framework
- Fine-grained
- Cannot differentiate between actions that effect only user-interface and those that are processed by back-end.
- Application framework
- Coarse-grained
- It is concerned with user-interface only and does not care what the rest of the application does.
From the differences we have seen till now it should come as no surprise that it is possibel to use JSF with an application framework like Struts.
Basically, all requests are processed by the JSF until it is clear that backend code needs to be invoked.
The control is then passed on to struts, and eventally comes back to JSF for rendering of the response.
Though there is some overlap between Struts and JSF regarding navigation and validation they are flexible enough that you can pick and which should be in charge of these tasks.
Services of JSF framework
MVC architecture
Data conversion
Validation and error handling
Internationalization
Custom components
Alternative renderers
Tool support
High level view of JSF
FAQ
What is JavaServer Faces technology?
What are the benefits of JavaServer Faces technology?
Who are the intended users of JavaServer Faces technology?
What is the difference between Struts and JSF?
How does JavaServer Faces technology relate to JavaServer Pages (JSP) technology?
A: JavaServer Faces technology, version 1.0 relies on JSP 1.2. Since JSP 2.0 is a superset of JSP 1.2, it is possible to use JavaServer Faces technology, version 1.0 with JSP 2.0. Future versions of the JavaServer Faces specification will be able to take better advantage of JSP 2.0.
Who is involved in developing the JavaServer Faces specification?A: A number of important industry players are collaborating with Sun to define the first draft of the JavaServer Faces specification.