JSF was
developed by Java Community Process(JCP). This is a community of web
application experts. These experts are from different groups like Jakarta
Struts, Oracle, Sun, IBM, ATG etc. They all collectively worked together to
take the best from existing technologies and removed problems. So their
collective effort brought a new technology named Java Server Faces (JSF).
Java Server
Faces or JSF for short, is the standard framework to simplify the process of
developing web application in java. It is a robust component framework, event
driven programming model. It offers a set of UI components, extensible
architecture, supports multiple client devices etc. Extensible means additional
functionality can be given on the top of JSF core i.e. we can customize the
functionality. JSF is vendor independent technology that is a standard to
be supported by whole software industry.
One of the
main feature of JSF is that it has not only been designed for coding experts but
for others also like :
1.
Page authors
Web designers have experience with graphic design. They can design look and
feel of web application in html/jsp using custom tag libraries of JSF.
2. Application
developers
Application developers can integrate this design with UI components. They program objects, event handles,
converters, validators.
3.
Component writers
Component developer can build custom UI components because of JSF’s
extensible and customizable nature. They can create their own components
directly from UI component classes or extending the standard components of JSF.
4.
Application architects
Application architects are responsible for designing web applications. Defining
page navigation, ensuring Scalability of application, configuring beans object
registration are the key points that an application architect handles.
5.
Tool vendors
JSF is well suited for tool vendors, for example Sun Java Studio Creator
application development tool, who provide tools that take advantages of JSF to
create UI easier.
In the past
many, web development frameworks came in to existence founded on servlet
and jsp. Struts emerged as a standard web application framework. It became
framework of choice because it came early in the market and provided
necessary features at the time but competitors continued providing
additional features that struts lacks. So it became necessary for java to
advent new standard framework with a powerful component model. This was the
reason for developing JSF technology. So main purpose of developing JSF was to
create a collection of APIs for the UI components with the capacity to manage
their states, handle events and validation.
Struts has an
option to migrate to JSF. The simplest option is to use JSF components and rest
as usual. This will enable them to take advantage of third party JSF
components. Main feature of JSF is ease of use. Developing web applications is
easier and faster than other frameworks like struts because JSF supports UI
components and easy event handling. Taking advantages of third party components
can reduce the cost of rewriting existing elements, minimize the time of
development.
New Features in JSF 1.2
The Java Server Faces 1.2 has released with many great
features and bug fixes. Here are the list of new features of JSF 1.2:
1.
Unified Expression Language (EL)
In the previous versions of JSF it was not possible to use JSTL code with the
JSF expression language. Now is JSF 1.2 you can use JSTL code with JSF. This
new feature of JSF 1.2 is know as Unified Expression Language. The Unified
Expression Language is great feature of JSF 1.2, which enables us to mix JSTL
code with the JSF expression language.
2. Component View Creation/content
Interweaving
3. Support for Multiple Render Kits
4. Integration with JSTL
5.
Other important featues of JSF 1.2
are:
o
XML Schema for the config files,
instead of using DTD
o
Security enhancements for client
side state saving
o
Solve the "duplicate button
press" problem
o
The
portlet related bug-fixes
This section introduced you with the new features of JSF. You can also
view the different releases of JSF at http://www.roseindia.net/jsf/jsf-versions.shtml
JavaServer Faces
technology is a server-side user interface component framework for Java
technology-based web applications.
The main components of JavaServer Faces technology are as follows:
The well-defined programming model and tag libraries significantly ease the
burden of building and maintaining web applications with server-side UIs. With
minimal effort, you can
As shown in Figure
17-1, the user interface you create with JavaServer Faces technology
(represented by myUI
in the
graphic) runs on the server and renders back to the client.
Figure 17-1 The UI Runs on the Server
The JSP page, myform.jsp
, is a JavaServer
Faces page, which is a JSP page that includes JavaServer Faces
tags. It expresses the user interface components by using custom tags defined
by JavaServer Faces technology. The UI for the web application (represented by myUI
in the figure) manages the objects
referenced by the JSP page. These objects include
This chapter gives an overview of JavaServer Faces
technology. After going over some of the primary benefits of using JavaServer
Faces technology and explaining what a JavaServer Faces application is, it
lists the various application development roles that users of this technology
fall into. It then describes a simple application and specifies which part of
the application the developers of each role work on. The chapter then moves on
to summarizing each of the main features of JavaServer Faces technology and how
the various pieces of an application that uses these features fit together.
Finally, this chapter uses a page from a simple application to summarize the
life cycle of a JavaServer Faces page.
JavaServer
Faces provides developers with the following main features:
JSF
provides the common plumbing for any Web application allowing you to
concentrate on your specific application (instead of worrying about things like
how to create a link from one page to another). This will become clearer as we
go along.
(From Wikipedia,
the free encyclopedia)
(JSF) is a Java-based Web application framework intended to
simplify development
of user
interfaces for Java EE applications. Unlike request-driven MVC web frameworks, JSF uses a component-based
approach. The state of UI components is saved when the client requests a new
page and restored when the request is returned. Out of the box, JSF uses JavaServer
Pages (JSP) for its display technology, but can also accommodate other
technologies (such as XUL
and Facelets).
JSF includes:
The JSF specification was developed under the Java Community Process as JSR 127,
which defined JSF 1.0 and 1.1, and JSR 252 which defined JSF 1.2.
Upcoming JSF 2.0 is being developed as JSR 314.
JSF is often mentioned together with Ajax, a Rich Internet application technology.
Ajax is a combination of technologies that makes it possible to create richer
user interfaces. The user interface components in the JSF reference
implementation and MyFaces were originally developed in HTML. Because JSF
supports multiple output formats, Ajax-enabled components can easily be added
to enrich JSF-based user interfaces. The JSF 2.0 specification intends to
improve support for Ajax by allowing UI logic to run partly on the client and
not only on the server, and by providing support for graceful degradation when JavaScript
is disabled in the browser.
The following companies and projects offer Ajax-based JSF implementations
or blueprints:
(Main article: Apache Struts)
Struts is a popular MVC framework from the Apache Software Foundation. It provides
page-at-a-time MVC and does not have a component model in the style of JSF.
Pages are mapped to models with a dispatch servlet (controller) piping input to
actions. Struts applications use JSPs to render views and are amenable to
mix-and-match jsp taglib use. (See also Apache
Beehive)
(Main article: WebObjects)
WebObjects is an early web-application framework
that was originally developed by NeXT Software, Inc. then acquired by Apple
Computer when it acquired NeXT. It contains an MVC architecture with a
component and event model and lifecycle similar to JSF. It is deployable
without J2EE (its original configuration), or can be deployed in a servlet
container — its dispatcher object acting as the entry-point of a
J2EE web application. Unlike JSF's default case, components are not defined in
JSP files but are in .wo
directories
containing any or all of html/xml/wml
template files, a .wod
file to map fields and actions
to Java code, and a .java
class. A
template file provides the rendering/layout and may include other WebObjects
components, rather than the delegated RenderKit
approach used by default in JSF. It is a halfway-point between the delegated
and directly-rendered approaches used in JSF.
WebObjects also includes a layered architecture
with one of the earliest Object-Relational Mapping frameworks, Enterprise Objects Framework.
Wotonomy
is a clean-room, open-source re-implementation of the
WebObjects frameworks licensed under LGPL. It attempts to implement all parts of WebObjects, and has
implemented the whole MVC web-GUI stack. As a clone of WebObjects, it differs
from JSF in identical ways, except where it is incomplete.
(Main article: Tapestry (programming))
Tapestry is an open-source framework for creating
dynamic, robust, scalable web applications in Java. Tapestry builds upon the
standard Java Servlet API, and so it works in any servlet container or application
server. Unlike JSF, Tapestry does not use JSP as the default view
technology — instead preferring an alternate templating engine that
allows for easy HTML preview and editing (similar to the JSF-based Facelets).
(Main article: ASP.NET)
JSF features a component based approach to
WebApplication development similar to ASP.NET from Microsoft. In
ASP.NET v1, component rendering code was bundled with the UI component, unlike
JSF, where rendering and component interfaces can be separated, thus allowing
for customization
of the renderer. ASP.NET v2 introduced the control adapter framework allowing
the default rendering to be overridden by third-party code.
Business code is connected to the UI components by
subscribing to events generated by the components and
stored in a separate file ("code behind"). Thus a typical ASP.NET
page consists of a (HTML)
file describing the visual page layout (design), and a file with the page logic
(code). Both files are treated as one single entity by Visual Studio.
According to the author of the book Core JSF,
JSF offers a means for Java to compete with ASP.Net/Visual Studio in the area
of Rapid application development (RAD).
In the latest still unreleased public draft for JEE6, Facelets (which was
designed specifically for Java Server Faces) will be adopted as the official
view technology for JSF 2.0. This will eliminate the well-known life-cycle
conflicts that existed with JSP forcing workarounds by Java developers.
Facelets will also allow easier tag creation using markup instead of Java code,
the chief complaint against JSF.
The new JSF developments will also see the usage of Java EE5 style
annotations such as @ManagedBean and @ManagedProperty which will lead to a
reduction in the size of the faces-config.xml config file. However,
navigation still needs to be done in the configuration file.
There will also be changes to the JSF lifecycle to account for AJAX which
will make AJAX development using JSF feel more natural.
The latest JSF release will also have built-in capability to handle
resources like images, CSS and Javascript and refer to them using logical names
and also grouping resources into libraries and versioning.
JSF 2.0 also includes a number of other changes like adding support for
events, RAILS_ENV style development stages and significantly expanding the
standard set of components
(Chris Schalk ,
Oracle Corporation, April, 2005)
JavaServer Faces (JSF) is a new
standard Java framework for building Web applications. It simplifies
development by providing a component-centric approach to developing Java Web
user interfaces. JavaServer Faces also appeals to a diverse audience of
Java/Web developers. "Corporate developers" and Web designers will
find that JSF development can be as simple as dragging and dropping user
interface (UI) components onto a page, while "systems developers"
will find that the rich and robust JSF API offers them unsurpassed power and
programming flexibility. JSF also ensures that applications are well designed
with greater maintainability by integrating the well established
Model-View-Controller (MVC) design pattern into it's architecture. Finally,
since JSF is a Java standard developed through Java Community Process (JCP),
development tools vendors are fully empowered to provide easy to use, visual,
and productive develop environments for JavaServer Faces.
One of the key advantages of JSF is
that it is both a Java Web user-interface standard as well as a framework that
firmly follows the Model-View-Controller(MVC) design pattern. This makes JSF
applications much more manageable because the user-interface code (View)
is cleanly separated from the application data and logic (Model). To
prepare the JSF context, which provides application data access to the pages,
and to guard against unauthorized or improper access of the pages, all user
interactions with the application are handled by a front-end "Faces"
servlet (Controller).
Figure 1: JavaServer Faces
Implementation of MVC
The Faces Controller servlet serves
as the link between the user and the JSF application. It operates within the
confines of a well defined JSF Lifecycle which dictates the entire flow
of events between user requests. For example, upon an initial Web request to
access a JSF application, the Faces controller servlet handles the request by
first preparing the JSF context, which is a Java object that holds all
application data. The controller then routes the user to the requested page.
The page usually renders application data from the JSF context using a simple
Expression Language. Upon subsequent requests, the controller updates any Model
data, providing any new input has been entered. JSF developers have
programmatic access to the entire JSF lifecycle at any time during its
execution thus affording a high degree of control over the application's
behavior at all times.
The true power of JavaServer Faces
lies in its user-interface component model where applications are merely built
from collections of components that can render themselves in diverse ways for
multiple client types. Vaguely similar to other proprietary technologies such
ASP.Net, JSF's UI Component model technology offers unprecendented productivity
by allowing the developer to construct Web user interfaces using pre-built
user-interface (UI) Components as opposed to having to construct the user
interface entirely from scratch. JSF UI Components come in many forms and can
be as simple as an outputLabel which simply displays text or as complex
as a dataTable which can represent a tabular data from collections of
data such as from a database table.
The JavaServer Faces specification
provides a set of base UI Components in its Reference Implementation which are
very useful on their own. These include two libraries of components such as the
"HTML" component library which largely mirrors the standard HTML
input elements along with a "Core" library which aids in common
application development tasks such as internationalization, and validating/converting
input data. In addition to providing a base library of UI Components, the JSF
API offers the ability to extend and create custom JSF UI Components providing
additional functionality above and beyond the base components.
Because of the richness and
flexibility of the JSF API, many Java developers are beginning to create new
JSF Component libraries and implementations. Oracle's ADF Faces is a
fully compliant JSF component library which offers a broad set of enhanced UI
Components for JSF application development. These include multiple renderers
per client type, advanced tables, color and date pickers along with a host of
general components such as menus, command buttons, shuttle choosers and
progress meters.
Figure 2: Oracle's ADF
Faces JSF UI Components
In addition to Oracle's ADF Faces there are other new JSF Component
Libraries beginning to appear from both the Open Source and software vendor
communities. MyFaces is an example of a new JSF UI Component Library
being offered as an Open Source project through Apache. Myfaces also serves as
an enhancement to the JSF base UI components in that they also have more
extensive UI capabilities such as integrated Tiles support, Javascript enabled
menus and Tree controls.
Figure 3: The Open Source
MyFaces Implementation and UI Component Library
One of the most compelling aspects
of JSF's UI Component technology is it's pluggable rendering capability. JSF UI
Components have the ability to render themselves differently depending on the
client type viewing the component. For example a HTML browser will view an
"HTML Browser Friendly" version of a particular UI Component whereas
a Wireless or WAP enabled micro-device would view a "WML friendly"
version of the same UI component! JSF makes this possible by de-coupling
the UI Component from its rendering logic making it possible to create multiple
renderers for the same UI Component. Different renders can be associated with
the UI Component and at runtime the UI component can decide which renderer to
use based on the requesting client type.
Figure 5: A Single ADF Faces
Table Component Rendering Differently for Wireless and HTML Clients
It should also be pointed out that
because of JSF's pluggable rendering capability it is possible for JSF UI
Components to render any kind of data be it markup, such as HTML, XML, WML
etc.., or binary data. For example UI Components can also render binary data
such as an image streams or different document types such as SVG, PDF and Word.
As the community of JSF developers
and enthusiasts continues to grow, there are now several Websites dedicated to
further empowering independent JSF development.. JSFCentral is an
example of a new Website solely dedicated to the JSF development community. It
contains JSF technical information, product/component information as well as a
vast listing of numerous JSF related articles.
Because JavaServer Faces is a
standard Java technology, software development tools are fully empowered to
offer advanced integrated development tools support for JavaServer Faces. This
greatly enhances JSF's ease of use and power in that multiple vendors are now
supporting JSF development to varying degrees. Oracle, Sun , Borland and IBM
each offer development environments for JavaServer Faces. Since development
tools vendors are competing at providing better, easier and more development
environments.
Figure 6: Oracle's
JDeveloper Offers a Productive, Visual JSF Development Experience
You will need the following to complete this
tutorial:
We will provide you with many of the project
files so that you don't need to create them yourself. We will be concentrating
primarily on the actual JSF application, not on creating Ant scripts or web.xml
files. These files will be provided for you. You will just need to copy and
paste content from this tutorial.
We are going to build a "Hello, world"
(actually "Welcome to JSF, <user>!") type application using
JSF. This should give you a solid start with JSF.
We will create two pages. The first page will
prompt a user to enter his or her name and the second page will show a
greeting. This is a sample of the input page:
and this is a sample of the result page:
We have provided you with a pre-made project
structure skeleton in an archive called jsfks.zip that you can download and unzip. After unzipping you should have the following structure:
jsfks
/ant
build.xml
/JavaSource
/WebContent
/WEB-INF
/classes
/lib
jsf-impl.jar
jsf-api.jar
faces-config.xml
web.xml
/pages
This is a typical skeleton structure for a Web
application like JSF. Now, let's go through the different parts of the skeleton
structure.
folder
or file |
explanation |
jsfks |
Project folder with
project name |
/ant |
This folder holds Ant
build scripts including a default build.xml file. |
/JavaSource |
This folder is where you
place your own Java source classes and properties files. |
/WebContent |
This folder holds the
actual Web application files used by the application server or servlet
container. |
/WEB-INF |
This folder inside the WebContent
folder holds files that are used as part of the runtime Web application but
are hidden from the browser. |
/classes |
This folder inside the WEB-INF
folder holds compiled Java classes along with properties files copied from JavaSource. |
/lib |
This folder inside the WEB-INF
folder holds libraries required by your application, for example, third party
Jar files. |
jsf-impl.jar |
These two files inside
the lib folder are library files included with the JavaServer Faces
v1.1 Reference Implementation. Every JSF application requires
these files. |
web.xml |
This file inside the WEB-INF
folder is the Web Application Deployment Descriptor for your application.
This is an XML file describing the servlets and other components that make up
your application. |
faces-config.xml |
This file inside the WEB-INF
folder is the JavaServer Faces configuration file. This file lists bean
resources and navigation rules. We will cover this file in more detail later.
|
pages |
This folder inside the WebContent
folder holds JSP and HTML presentation pages. |
We have already provided you with two complete
project files in the the project, web.xml and build.xml, so that
you don't have to spend time creating these. (This tutorial is not about
creating these kinds of files.)
We will complete the following steps:
But first note that we have also provided you
with the finished application in case you just want to just run it and skip
most of the steps. If you want to do this, you can download and unzip jsfks-done.zip. Then skip to the "compile" step and go from there.
Create
the inputname.jsp and greeting.jsp files in WebContent/pages/.
You only need to create the JSP files. The directory structure already exists.
These
files will act as place holders for now. We will complete the content of the
files a little bit later.
Now that
we have the two JSP pages, we can create a navigation rule.
Navigation
is the heart of JavaServer Faces. The navigation rule for this application is
described in the faces-config.xml file. This file already exists in the
skeleton directory structure. You just need to create its contents.
In our
application, we just want to go from inputname.jsp to greeting.jsp.
As a diagram, it would look something like this:
Image from Exadel Studio Pro
The navigation rule shown in the picture is defined
below. The rule says that from the view (page) inputname.jsp go to the
view (page) greeting.jsp, if the "outcome" of executing inputname.jsp
is greeting. And that's all there is to this.
<navigation-rule>
<from-view-id>/pages/inputname.jsp</from-view-id>
<navigation-case>
<from-outcome>greeting</from-outcome>
<to-view-id>/pages/greeting.jsp</to-view-id>
</navigation-case>
</navigation-rule>
This is, of course, a very simple navigation
rule. You can easily create more complex ones. To read more about navigation
rules, visit the JSP Navigation Example forum item.
Next, we will create a jsfks folder
inside the JavaSource folder. Inside this jsfks folder, we will
create a PersonBean.java file. This class is straight-forward. It's a
simple Java bean with one attribute and setter/getter methods. The bean simply
captures the name entered by a user after the user clicks the submit button.
This way the bean provides a bridge between the JSP page and the application
logic. (Please note that the field name in the JSP file must exactly match the
attribute name in the bean.)
Put this code in the file:
package jsfks;
public class PersonBean {
String personName;
/**
* @return Person Name
*/
public String getPersonName() {
return personName;
}
/**
* @param Person Name
*/
public void setPersonName(String name) {
personName = name;
}
}
Later you will see how to "connect"
this bean with the JSP page.
Now, the second part of faces-config.xml
describes our Java bean that we created in the previous steps. This section
defines a bean name PersonBean. The next line is the full class name, jsfks.PersonBean.
request sets the bean scope in the application.
<managed-bean>
<managed-bean-name>personBean</managed-bean-name>
<managed-bean-class>jsfks.PersonBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
Your final faces-config.xml file should
look like this:
<?xml version="1.0"?>
<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
"http://java.sun.com/dtd/web-facesconfig_1_1.dtd">
<faces-config>
<navigation-rule>
<from-view-id>/pages/inputname.jsp</from-view-id>
<navigation-case>
<from-outcome>greeting</from-outcome>
<to-view-id>/pages/greeting.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<managed-bean>
<managed-bean-name>personBean</managed-bean-name>
<managed-bean-class>jsfks.PersonBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
</faces-config>
A
properties file is just a file with param=value pairs. We use the messages
stored in the properties file in our JSP pages. Keeping the messages separate
from the JSP page allows us to quickly modify the messages without editing the
JSP page.
Let's
create a bundle folder in the JavaSource/jsfks folder and then a messages.properties
file in the bundle folder. We need to place it in the JavaSource
folder so that during project compilation, this properties file will be copied
to the classes folder where the runtime can find it.
Put this text in the properties file:
inputname_header=JSF KickStart
prompt=Tell us your name:
greeting_text=Welcome to JSF
button_text=Say Hello
sign=!
We now have everything to create the JSP pages.
Two pages should already have been created in jsks/WebContent/pages.
Put the following coding into this file:
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:loadBundle basename="jsfks.bundle.messages" var="msg"/>
<html>
<head>
<title>enter your name page</title>
</head>
<body>
<f:view>
<h1>
<h:outputText value="#{msg.inputname_header}"/>
</h1>
<h:form id="helloForm">
<h:outputText value="#{msg.prompt}"/>
<h:inputText value="#{personBean.personName}" />
<h:commandButton action="greeting" value="#{msg.button_text}" />
</h:form>
</f:view>
</body>
</html>
Now, let's explain the important sections in
this file after displaying the code for each section starting from the top.
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:loadBundle basename="jsfks.bundle.messages" var="msg"/>
The first line of these
three is a directive that tells us where to find JSF tags that define HTML
elements and the second directive tells us where to find JSF tags that define
core JSF elements. The third line loads our properties file (resource bundle)
that holds messages that we want to display in our JSP page.
<h:outputText value="#{msg.inputname_header}"/>
This tag simply tells us to
look in the resource bundle that we defined at the top of the page. Then, look
up the value for inputname_header in that file and print it here.
1 <h:form id="helloForm">
2 <h:outputText value="#{msg.prompt}"/>
3 <h:inputText id="name" value="#{personBean.personName}" />
4 <h:commandButton action="greeting" value="#{msg.button_text}" />
5 </h:form>
Line 1. Creates an HTML
form using JSF tags.
Line 2. Prints a message from the properties file using the value of prompt.
Line 3. Creates an HTML input text box. The id is just the id of this
field. In the value attribute we connect (bind) this field to the
managed bean attribute that we created before.
Line 4. JSF tags for the HTML form's submit button. The button's value is being
retrieved from the properties file. While the button's action attribute
is set to greeting which matches the navigation-outcome in faces-config.xml
file. That's how JSF knows where to go next.
Put this coding inside the second JSP file:
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:loadBundle basename="jsfks.bundle.messages" var="msg"/>
<html>
<head>
<title>greeting page</title>
</head>
<body>
<f:view>
<h3>
<h:outputText value="#{msg.greeting_text}" />,
<h:outputText value="#{personBean.personName}" />
<h:outputText value="#{msg.sign}" />
</h3>
</f:view>
</body>
</html>
This page is very simple. The first three lines
are identical to our first page. Theses lines import JSF tag libraries and our
properties file (resource bundle) with the messages.
The main code of interest to us is between the <h3>..</h3>
tags. The first line will take a message from the resource bundle and print it
on the page. The second line will access a Java bean, specifically the bean
attribute personName, and also print its contents on the page.
Once this page is displayed in a Web browser,
you will see something like this:
Welcome to JSF, name!
We will now create a third JSP file that doesn't
actually function as a presentation page. It uses a JSP tag to
"forward" to the inputname.jsp page.
Create the index.jsp file inside the WebContent
folder. Note that this file is not created in the pages folder
like the previous JSP files.
Having an index.jsp file will allow us to
start the application like this:
http://localhost:8080/jsfks/
Now, put this coding into the file:
<html>
<body>
<jsp:forward page="/pages/inputname.jsf" />
</body>
</html>
If you look at the path for
the forward, you'll notice the file suffix is .jsf and not .jsp.
This is used here, because in the web.xml
file for the application *.jsf
is the URL pattern used to signal that the forwarded
page should be handled by the JavaServer Faces servlet within Tomcat.
We are almost done with this example.
An Ant build script is provided for you. To
build the application run the build.xml script from the ant folder:
ant build
Before you can run this application within the
servlet container, we need to deploy it. We will use null (link) deployment to
deploy the application in-place. To do this we need to register a context in
Tomcat's {TomcatHome}\conf\server.xml file.
To do this, insert this code:
<Context debug="0"
docBase="Path_to_WebContent"
path="/jsfks" reloadable="true"/>
near the end of the server.xml
file within the Host element just before the closing </Host>
tag. Of course, Path_to_WebContent needs to be replaced with the exact
path on your system to the WebContent folder inside the jsfks
folder (for example, C:/examples/jsfks/WebContent
).
Next, start the Tomcat server (probably using
the script startup.bat in Tomcat's bin directory). When Tomcat is
done loading, launch a web browser and enter: http://localhost:8080/jsfks.
(Port 8080 is the default port in Tomcat. Your setup, though, might possibly be
different).
It's always a good learning experience to modify
the application after you are done. Let's try a simple modification.
Let's say we want to initialize the name
value. In other words, when we first run the application, the input text field
should have a value already displayed.
It is very simply to do this in JSF. We can
provide an initial value in the faces-config.xml file, in the managed
bean section. The lines in bold from this section show what we need to add.
These lines declare a managed bean property of type java.lang.String and
then set its value to JavaJoe.
<managed-bean>
<managed-bean-name>personBean</managed-bean-name>
<managed-bean-class>jsfks.PersonBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>personName</property-name>
<property-class>java.lang.String</property-class>
<value>JavaJoe</value>
</managed-property>
</managed-bean>
You don't even need to recompile anything, just
restart Tomcat and launch the application.
We are
going to build on the "A Simple JavaServer Faces
Application" tutorial to
show you how to use standard validation features in JSF. If you haven't done
this tutorial already, you can just download the finished application for that tutorial and use it as the basis for
proceeding with this tutorial.
The
application built in the "A Simple JavaServer Faces Application"
tutorial prompts the user to enter a name and then presents a greeting that
uses that name. Now we want to make sure that valid input is entered before the
submit button is even clicked. Let's see how it's done.
1. Adding code to check for no input for a name
2. Adding code to check for reasonable length of input
for a name
3. Adding code for printing error messages
4.
Compiling
5.
Deploying
6.
Running
But, first note that we have also provided you
with the finished application in case you just want to just run it and skip
most of the steps. If you want to do this, you can download and unzip jsfks-validation-done.zip. Then skip
to the "compile" step and go from there.
We want
to make sure that no empty name is submitted. To do that, we will use the required
attribute for the inputText tag in inputname.jsp. Setting this
attribute to true will ensure that no empty value is submitted.
First,
open this JSP file in the jsfks/WebContent/pages folder. In the coding
for this page, we only need to add the required attribute as shown below
in bold. That's all you need to do to make the field required.
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:loadBundle basename="jsfks.bundle.messages" var="msg"/>
<html>
<head>
<title>enter your name page</title>
</head>
<body>
<f:view>
<h1>
<h:outputText value="#{msg.inputname_header}"/>
</h1>
<h:form id="helloForm">
<h:outputText value="#{msg.prompt}"/>
<h:inputText value="#{personBean.personName}" required="true"/>
<h:commandButton action="greeting" value="#{msg.button_text}" />
</h:form>
</f:view>
</body>
</html>
We also
want to make sure that the name value is at least 3 characters long but not
more than 10 long. To do that, we will use the f:validateLength tag in
this same inputname.jsp file.
See the
modified code in bold. Notice that we now close the inputText tag
differently. Instead of being an "empty" element, it now has the f:validateLength
element as a child element.
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:loadBundle basename="jsfks.bundle.messages" var="msg"/>
<html>
<head>
<title>enter your name page</title>
</head>
<body>
<f:view>
<h1>
<h:outputText value="#{msg.inputname_header}"/>
</h1>
<h:form id="helloForm">
<h:outputText value="#{msg.prompt}"/>
<h:inputText value="#{personBean.personName}" required="true">
<f:validateLength minimum="2" maximum="10"/>
</h:inputText>
<h:commandButton action="greeting" value="#{msg.button_text}" />
</h:form>
</f:view>
</body>
</html>
That's all that we have to do.
That last thing that we need to do is to add
some kind of error message warning to the user. JSF provides a special tag to
print messages.
As a last change to this file, we have added the
h:messages tag and also set the color for the messages using the style
attribute. This addition is shown in bold.
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:loadBundle basename="jsfks.bundle.messages" var="msg"/>
<html>
<head>
<title>enter your name page</title>
</head>
<body>
<f:view>
<h1>
<h:outputText value="#{msg.inputname_header}"/>
</h1>
<p>
<h:messages style="color:darkred"/>
</p>
<h:form id="helloForm">
<h:outputText value="#{msg.prompt}"/>
<h:inputText value="#{personBean.personName}" required="true">
<f:validateLength minimum="3" maximum="10"/>
</h:inputText>
<h:commandButton action="greeting" value="#{msg.button_text}" />
</h:form>
</f:view>
</body>
</html>
An Ant build script is provided for you. To
build the application run the build.xml script from the ant folder.
ant build
Before
you can run this application within the servlet container, you need to deploy
it. If you have already done the previous "A Simple JavaServer Faces
Application" tutorial, you've already taken care of this. Otherwise, you
will need to use null (link) deployment to deploy the application in-place by
register a context in Tomcat's {TomcatHome}\conf\server.xml file.
To do
this, insert this code:
<Context debug="0"
docBase="Path_to_WebContent"
path="/jsfks" reloadable="true"/>
near the end of the server.xml file within the Host
element just before the closing </Host> tag. Of course, Path_to_WebContent
needs to be replaced with the exact path on your system to the WebContent
folder inside the jsfks folder (for example, C:/examples/jsfks/WebContent
).
Next,
start the Tomcat server (probably using the script startup.bat in
Tomcat's bin directory). When Tomcat is done loading, launch a web
browser and enter: http://localhost:8080/jsfks. (Port 8080 is the
default port in Tomcat. Your setup, though, might possibly be different).
The Lifecycle object processes a JSF request (encapsulated in the FacesContext
object; the FacesContext is the object that is read and modified by Lifecycle
during processing) in six phases, executed in the following order:
The Apply Request Values, Process
Validations, Update Model Values, and Invoke Application phases in the request
processing lifecycle may queue events in the FacesContext instance associated
with the current request. Therefore, the JSF implementation must handle these
events after these phases.
Between two phases, the Lifecycle object checks any event listener
that needs to be called. When writing an event listener, you can choose after
which phase the listener should be executed. Alternatively, you can write an
event listener that is called after various phases.
Figure 3 illustrates the processing of a JSF
request through these phases. The smaller boxes that are labeled “Process
Events” indicate the steps that the Lifecycle
object takes to execute event listeners.
Figure 3 The phases of
the request processing lifecycle
Note
that an event listener can change the course of the processing flow by
indicating to the Lifecycle object that the processing should
jump to the last phase or be terminated immediately after the current event
processing
You can easily configure a JSF application via an
application configuration file. In this file, you can register JavaBeans used
in the application, define the program-control flow by specifying
page-navigation rules, register custom components, and perform other
configuration tasks. The application configuration file is an XML file and can
be declared in several places. The easiest way to use this file is to put it in
the WEB-INF directory and call it faces-config.xml. The root element of an application
configuration file is faces-config. Here is the skeleton of an
application configuration file:
<?xml version="1.0"? > |
There are a number of aspects of a JSF
application that can be configured in the application configuration file. Here,
we will focus on how to register JavaBeans (as used in the examples later in
this chapter).
In a JSP page, you can use the jsp:useBean action to tell
the JSP container that you are using the JavaBean class specified in the class
attribute of the jsp:useBean action, such as the following:
<jsp:useBean id="numberBean" class="ch02.NumberBean"
scope="session" />
This tells the Web container to load the JavaBean
class and create an instance of it when the JSP page is called. The jsp:useBean
action needs to be declared in only one page, and it will be usable in all the
JSP pages in the same application. A JSF application allows you to do this
instead of registering a JavaBean in the application configuration file.
However, there is a drawback when using <jsp:useBean>. If a page other than the one containing the jsp:useBean
action is called before the page that does use the element is called, the Web
container will throw an exception. This is because the other page is trying to
use a JavaBean that has not been created. If you register the JavaBean in the
application configuration file, you will not have this problem. For each
JavaBean you want to register in the application configuration file, you use
the managed-bean tag inside the faces-config element. Inside the managed-bean
element, you have the following subelements:
Here is an example of a managed-bean element:
<managed-bean> |
The managed-bean element in this example is of type myPackage.MyBean and can be
referred to as MyBean from any JSP page in the JSF application. The scope of
the bean is session, meaning that an instance of this bean is created at the
beginning of a user session. The managed-bean element will be explained further
in Chapter 3.
Later in this chapter, in the “Creating the Page Navigation
Example” section, you will see how to use an application configuration
file to define page-navigation rules in a JSF application with many pages
Building a JSF application requires the following three steps:
NOTE The JSF implementation also provides a
default event listener for page navigation that can be configured easily. You
should not write an event listener that tampers with page navigation.
These steps do not need to happen in a particular order. In fact, they can
occur simultaneously in a project with a clear separation of labor. Now,
let’s take a closer look at each of these three steps.
Authoring JSP Pages
Authoring a JSP page requires you to be familiar with the standard JSF
components. JSF components are discussed in detail in Chapters 4 and 5. The
following components are used in the examples in this chapter:
In a JSP page, you use custom tags that represent JSF components. These
custom tags are part of two custom tag libraries, HTML and Core, and are
included in the WEB-INF/lib directory of the application
directory (as discussed in the “Introduction” to this book). The
tag library descriptors (TLD files) for these libraries have also been included
in the .jar files, so you do not need to worry about them.
To use the custom tags that represent JSF components, you need the following
two taglib directives on top of every JSP page in the JSF application:
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
All custom tags representing the component must be enclosed in the use_faces tags of the Core custom tag library:
<f:use_faces>
<%-- custom tags representing JSF components here --%>
</f:use_faces>
<?xml:namespace prefix = f /><f:use_faces><%-- custom tags representing JSF components here --%></f:use_faces>
The custom tags representing JSF components are discussed in Chapters 4
and 5. The following are some of the custom tags used in the examples in this
chapter: