JSF - Java Server Faces Tutorials Complete Java Server Faces (JSF) Tutorial - JSF Tutorials
JSF - Java Server Faces Tutorials Complete Java Server Faces (JSF) Tutorial - JSF Tutorials
JSF Tutorials at Rose India covers everything you need to know about JSF. You can learn
JSF fast by following the Java Server Faces tutorials provided here.
Introduction To JSF
This tutorial explains “What JSF is”, “How it works”, ”What are its benefits”, ”How to
work with JSF” in easy and sequential manner. This is a complete guide to the new JSF
technology of JAVA.
JSF Overview
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.
What Is JSF?
JSF is new standard framework, developed through Java Community Process (JCP), that
makes it easy to build user interfaces for java web applications by assembling reusable
components in a page.
JSF Releases
JSF Features
JSF Components
Components in JSF are elements like text box , button , table that are used to create UI of
JSF Applications. These are objects that manage interaction with a user.
JSF Tags
JSF application typically uses JSP pages to represent views. JSF provides useful special
tags to enhance these views. Each tag gives rise to an associated component.
JSF Architecture
JSF was developed integrating MVC design pattern so that applications can be designed
well with greater maintainability.
JSF Renderers
After creating JSF components, it is also necessary for each component to be rendered to
the client so that it can be visible to the client’s device. Each of the tag gives rise to an
associated component .
JSF Installation
JavaServer Faces or JSF is great technology for the development of user interfaces for
web applications. The Java Server Faces specification is defined by JSR 127 of the Java
Community Process. JSF Tutorial By R.S.RAMASWAMY
Email: [email protected]
Part1
INTRODUCING JAVA SERVER FACES (JSF).
Part 2
In this second part of the tutorial, basics steps to install and run the examples are
explained.
Part 3
In this part of the JSF tutorial 'backing beans', event-handling, validation and discussed.
JSF Tutorial By Farihah Noushene
Email: [email protected]
Part1
In this first part of the tutorial, author, explores the examples provided by SUN, in the
JSF package.
Part 2
In this second part of the author shows how we can create our own components based on
the model for chart, Menu, Tree and Tabbed-pane provided by SUN documentation in
JSF.
Download JSF Books
Here, You will come across some books on JSF which may be free or not but all books
are referred for the best suggestion. You can learn more and more about JSF in a right
flow of the sequence of topics.
JSF Tutorial
This tutorial explains “What JSF is”, “How it works”, ”What are its benefits”,
”How to work with JSF” in easy and sequential manner. This is a complete guide to the
new JSF technology of JAVA. This tutorial contains all you will need like how to create
user interface components, how to connect them to business objects, how to create
deployment descriptors that binds everything together, how to handle events generated by
the action on components etc. This tutorial contains readable and interesting content
organized in proper and sequential manner. Each concept has been explained by simple
examples so that you can understand easily and implement immediately into your java
web application. It provides coverage of following key JSF concepts:
User Interface(UI) components
Renderers
Backing beans
Validators
Converters
Navigation
Event handling
Expession language
Messages
Our JSF tutorial comes with free source code and required configuration files that makes
JSF learning easy and fast. You can download all the codes in easy to use zip format from
our website. Latest source code can be downloaded from index page.
We will describe you how to implement all these concepts in order to create a robust JSF
web application.
JSF Overview
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 :
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.
Application developers
Application developers can integrate this design with UI components. They program
objects, event handles, converters, validators.
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.
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.
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.
What is JSF?
JSF is new standard framework , developed through Java Community Process (JCP) , that
makes it easy to build user interfaces for java web applications by assembling reusable
components in a page. You can think of JSF framework as a toolbox that is full of
ready to use components where you can quickly and easily add and reuse these
components many times in a page and capture events generated by actions on these
components. So JSF applications are event driven. You typically embed components in a
jsp page using custom tags defined by JSF technology and use the framework to handle
navigation from one page to another. Components can be nested within another
component , for example, input box, button in a form.
The UI (user interface) created using JSF technology runs on server and output is shown
to the client. Goal of JSF is to create web applications faster and easier. Developers can
focus on UI components, events handling, backing beans and their interactions rather
than request, response and markup. JSF hides complexities to enable developers to focus
on their own specific work.
JSF Features
JSF is a rich featured framework of JAVA technology. JSF provides a set of standard
features that makes it a powerful and standard among the existing technologies available
for the development of web application based on java technologies. Some of the features
have been given below to justify the above statement.
JSF is standard web user interface framework for Java.
Built on top of Servlet API.
JSF is a component framework
UI components are stored on the server.
Easy use of third party components.
Event driven programming model.
Events generated by user are handled on the server.
Navigation handling.
Can automatically synchronize UI components .
JSF supports multiple client devices.
JSF has extensible architecture.
International language support.
Extensive tool support (Sun, Oracle , IBM etc.).
Rapid application development approach.
A short view of jsf features has been given above. Its main features are component
model, event driven, extensible architecture, rapid application development. All of the
features will be described in subsequent topics.
How JSF Fits For Web Applications?
JSF best suits in to the java web development environment because of reasons described
below : JSF has many advantages over other existing frameworks that makes it a better
choice for web application development. Some of the reasons are below:
An extensible architecture:
JSF architecture has been designed to be extensible.Extensible means additional
functionality can be given on the top of JSF core i.e. we can customize the functionality.
JSF UI components are customizable and reusable elements. You can extend standard
components and create your own complex components like stylish calendar, menu bar
etc.
JSF Components
Components in JSF are elements like text box, button, table etc.. that are used to create
UI of JSF Applications. These are objects that manage interaction with a user. You can
create :
Standard UI Components:
JSF contains its basic set of UI components like text fields, check boxes , list boxes,
panel , label, radio button etc. These are called standard components. For example:
Custom UI Components:
Generally UI designers need some different , stylish components like fancy calendar,
tabbed panes . These types of components are not standard JSF components. JSF
provides this additional facility to let you create and use your own set of reusable
components .These components are called custom components.
One of the greatest power of JSF is to support third party components .Third party
components are custom components created by another vendor. Several components are
available in the market ,some of them are commercial and some are open source . You
can use these pre-built & enhanced components in UI of your web application .Suppose u
need a stylish calendar , u have an option to take it from third party rather than creating
it .This will help you to save your time & cost creating effective & robust UI and to
concentrate on business logic part of web application.
If u want to create custom components then its necessary to either implement
UIComponent interface or extend UIComponentBase class that provides default behavior
of components. These may be responsible for its own display or the renderer is used for
its display. These components are stored in component tree on the server and they
maintain state in between client requests. These components are manipulated on the sever
in java code.
So the final conclusion of using third party components is that a more attractive , robust
and functional UI can be created with fewer time, cost and man power.
JSF Tags
JSF application typically uses JSP pages to represent views. JSF provides useful special
tags to enhance these views. Each tag gives rise to an associated component. JSF
provides 43 tags in two standard JSF tag libraries:
In the above code fragment we have imported two JSF tag libraries with the help of taglib
directive. JSF Core Tag Library contains set of JSF core tags while JSF Html Tags
Library contains set of html tags. Prefix is used to use tags defined in tag library. Here we
are using conventional names f and h for Core & Html tags respectively. We have the
choice to choose any name for the prefixes.
JSF Html Tags:
These tags represent html components like text fields, buttons, form.
Html tags can be divided into following categories:
Some examples have been given below to understand how to use these tags and its
attributes:
<h:commandButton
id="submit"
value="go"
action="nextPage">
</h:commandButton>
creates a command button where value attribute sets the value that is displayed on the
button when it is rendered and action attribute is used to invoke a method defined in
backing bean when a user does an action on the component .According to the return of
the invoked method it is determined which view is to be displayed next.
These tags allows you to take advantages of features of JSF framework, like validation,
conversion , event handling. Core library is stepchild of Html library. i.e. core library
supports the html library. Core tag library also contains tags for views and sub-views ,
loading resource bundle, adding arbitrary text to a page. Some examples of JSF core tags
are:
Some examples have been given below to understand how to use these tags:
<f:view locale="en">
<h:outputText value="label" />
</f:view>
f: view tag is used to create top level view and is a container for all JSF component tags
on a page. Where locale attribute provides several options for presenting localized views
of your application. Here "en" represents English and if we give velue "fr" to locale
attribute then french view will be displayed. So this attribute is useful for
internationalization purpose.
<f:view>
<h1>head</h1>
<p>view</p>
<f:subview id="sub_id">
<c:import url="second.jsp" />
</f:subview>
</f:view>
Here f:subview tag is like container for the JSF components contained in an included JSP
page (second.jsp).
<h:inputText id="txt_id"
value="txt_value">
<f:validator validatorId="Txt_Validator" />
</h:inputText>
The Validator tag registers a Validator on the component associated with the enclosing
tag. In validatorId field, we give the value of one of the validator-id element of a
validator in your Faces configuration file.
This phase starts when a user requests a JSF page by clicking a link, button etc. In this
phase view generation of the page, binding of components to its event handlers and
validators are performed and view is saved in the FacesContext object. The FacesContext
object contains all the state information JSF needs to manage the GUI component's state
for the current request in the current session. The FacesContext stores the view in its
viewRoot property.All the JSF components are contained by viewRoot for the current
view ID. Component tree of a page is newly built or restored.
A request comes through the FacesServlet controller. The controller checks the request
and takes the view ID i.e. name of the JSP page. View ID is used to look up the
components in the current view. JSF controller uses this ID if the view already exists . If
the view doesn't already exist, the JSF controller creates it. The created view contains all
components.
The purpose of this phase is for each component to retrieve its current state. After
restoring of component tree in previous phase each component in the tree retrieves its
new value and store it locally. Component values are typically retrieved from the request
parameters.If immediate attribute of a component is set to true, then the validation,
conversion, and events associated with the component is processed in this phase.
If a component's immediate event handling property is not set to true, the values are
converted. Suppose field is bound to be an Integer property, the value is converted to an
Integer. An error message associated with the component is generated if this conversion
fails, and queued in the FacesContext. This message will be displayed during the render
response phase, along with any validation errors resulting from next process validation
phase.
At the end of this phase, the components are set to their new values, and messages and
events have been queued.
During this phase local values stored for the component in the tree are compared to the
validation rules registered for the components. If local value is invalid, an error message
is added to FacesContext, and the component is treated invalid then JSF proceeds to the
render response phase and display the current view showing the validation error
messages. If there were conversion errors from the apply request values phase, the
messages for these errors are also displayed. If there are no validation errors, JSF
proceeds ahead to the update model values phase.
After confirming that data is valid in the previous phase local values of components can
be set to corresponding server side object properties i.e. backing beans. So bean
properties will be updated .If the local data cannot be converted to the types specified by
the bean properties, the life cycle proceeds directly to the render response phase and
errors are displayed.
Before this phase the component values have been converted, validated, and applied to
the bean objects, so you can now use them to execute the application's business logic.
Application-level code is executed such as submitting a form or linking to another
page.For example user moves to the next page you will have to create a mapping in the
faces-config.xml file. Once this navigation occurs, you move to the final phase of the
lifecycle.
JSF Architecture
JSF was developed integrating MVC design pattern so that applications can be designed
well with greater maintainability. To understand this fact we need to understand what is
MVC design pattern, how MVC helps to design an application well and how can we
make our web application easy to maintain.
The MVC design pattern splits an application design into three separate parts:
MVC model’s purpose is to separate model and presentation to enable developers to set
focus on their core skills and collaborate more clearly. If you have to create many pages
for presentation then you have to concentrate only on view layer rather than model and
controller layer because you can reuse code for controller and model.
In the same way if you want to change the code for model then you typically need not to
change view layer.
Controllers are used to process user actions. In this process layer model and views may
be changed.
The best advantages of JSF is that it is both a Java Web user-interface standard and a
framework that fits well with the Model-View-Controller (MVC) design pattern. It offers
a clean separation between presentation and behavior. MVC pattern helps persons of
different skill sets to work separately so tasks can be completed in parallel. UI can be
created by page author using reusable UI components and business logic part can be
implemented using managed beans.
JSF Renderers
After creating JSF components, it is also necessary for each component to be rendered to
the client so that it can be visible to the client’s device. Each of the tag gives rise to an
associated component. A renderer is a type of class that is responsible for encoding and
decoding components. Encoding displays the component while decoding translates the
user’s input into components value i.e. transform it into values the component can
understand.
Now a days there are many devices that are web enabled. So application developers have
challenge to develop components that can work across various platforms. For example, if
we have an application that works on standard web browser and we want to extend it to
make it enable to work on a WAP device. So, to handle this case we need components to
be rendered in more than one way. Here JSF can help you . It is a simple task for JSF.
Solution is to develop separate renderers for the component. JSF components use
different renderers depending on the device used.
Encoding:
For example: Suppose we have used h:inputText tag . So the renderer of the component
associated with this tag produces the following output:
This is called encoding. The encoded page is sent to the browser and displayed.
Decoding:
Now if fields in form are filled by user and page is submitted by clicking the button, the
browser sends the form data to the web server as a “POST” request”. POST” request
contains form data and URL of the form. This form data is placed in hash table and can
be accessed by all components. Each component gets a chance to look that hash table to
interpret the form data. This is called decoding.
Html output Tag handler asks each component to render itself. Tag handler call two
rendering methods for each component :
2-encodeEnd() in doEndTag().
Opening tag, like <form> , is written by encodeBegin() method and closing tage </form>,
is written by encodeEnd() method. Single tag, like <input>, that dosen’t require separate
opening and closing tag is also written by encodeEnd() method.
JSF tag handler may call third rendering method encodeChildren().if rendersChilden
property of component is set to true i.e. if component has child components(compound
component). For example: Html table component composed of input field components as
column values for each row. So for a complex component tag handler calls
encodeBegin(), then encodeChildren() and encodeEnd() on the component.If the child
component also has its own children component then encodeChildren() method calls
encodeBegin() and encodeEnd() on the child component.
Some components renders itself (Direct rendering) and some components uses renderer
to render itself (Delegated rendering). So both are different. If component uses renderer,
then JSF calls encoding methods of the renderer, not the encoding method of the
component. Which renderer will be used is determined by getRenderer() method of the
component. So rendering of UI components is separated out that makes it pluggable with
other possible rendering i.e.if we want a new functionality, like a new look and feel or
rendering output to different client types, then its easy to add or plug a new renderer.
Render kit :
Component classes generally transfer the task of generating output to the renderer. All
JSF components follow it. Render kit is a set of related renderers.
javax.faces.render.RenderKit is the class which represents the render kit.The default
render kit contains renderers for html but it’s up to you to make it for other markup
languages.Render kit can implement a skin (a look & feel).Render kit can target a
specific device like phone, PC or markup language like HTML,WML, SVG. This is one
of the best benefit of JSF because JSF doesn't limit to any device or markup.
<render-kit>
<renderer>
<renderer-type>........</renderer-type>
<renderer-class>........</renderer-class>
</renderer>
</render-kit>
The information mentioned in configuration file registers the renderer with the default
html RenderKit. UI component's geRendererType() method is called that returns a string
to identify the type of renderer that would be used by component and to see if it should
delegate rendering to a renderer. If no matching render type is found then component
renders itself without delegating to any renderer.
<render-kit>
<render-kit-id>...........</render-kit-id>
<render-kit-class>........</render-kit-class>
<renderer>
<renderer-type>.........</renderer-type>
<renderer-class>........</renderer-class>
</renderer>
</render-kit>
In this case, configuration file shows how to register the renderer (for ex.
ButtonRenderer) specified in <renderer-class> which renders a component (for ex.
Button) specified in <renderer-type> to a client (for ex. SVG) specified in <render-kit-
id>.
This is the simplest JSF application that enables even a novice to understand easily the
steps to follow to create own JSF application. In this example we will explain all you
need, to develop this application like how to use JSF tags in JSP pages, how to configure
the application through faces-config.xml, and web.xml, directory structure of the
application etc. A detailed explanation of this example will definitely form a basis for
you to develop your own JSF application with more advanced functionality of JSF.
In this application the first page that comes in front of user contains an input text and a
command button components. User enters name in the input text and press the button. As
soon as the button is pressed next page is shown with the greeting content to the user.
Steps Followed :
To understand clearly where to place which file, directory structure of this application
will help you a lot. So have a look on it below:
In this application we used JDK 1.6.0 and TOMCAT 5.5.23 to deploy and run this
application. Install and configure TOMCAT for JSF.
Directories :
In tomcat, web applications are placed within webapps folder. Now we are going to start
creating "SimpleHelloByEnteringName" application so the first step is to create a folder
in web apps with the name "SimpleHelloByEnteringName". This is the root directory of
the application. Now create WEB-INF folder in root directory and place web.xml and
faces-config.xml file.
Configuration files :
web.xml :
You can get web.xml file from WEB-INF folder of any other application available in
TOMCAT by default or you can create yourself with the same name and extention of the
file i.e. "web.xml". If you are creating this file then take care of mentioning version of
xml. For ex. <?xml version="1.0"?> at the top of file and after that all elements will be
written within web-app opening and closing tag i.e.<web-app> and </web-app> . So the
root element of this file is <web-app>.
So if you want to create this file then write above code in notepad and save it with name
"web.xml" in the WEB-INF folder of your application. After creating and placing this
file to the appropriate position, we have to add some elements within web-app tag. How
and why we will write those elements will be described later in this section.
faces-config.xml
Now we come to the second file faces-config.xml that will be in the same place where
web.xml is i.e. WEB-INF folder. Here also you have to take care of mentioning version
of xml as we did in web.xml file. All tag elements will be within faces-config opening
and closing tag i.e. <faces-config> and </faces-config>. So the root element of this file is
<faces-config> tag.
You can create this file also by your own or copy from other JSF Application . If you
want to create this file then you can write the above code in notepad and save it with the
name "faces-config.xml" in WEB-INF folder of your application. After creating and
placing this file to the appropriate position, we have to add some elements within faces-
config tag. How we will write those elements will be described later in this section.
So now there will be two xml files web.xml and faces-config.xml in WEB-INF directory.
Now our first step is to create view for the application. For this we have created three JSP
files given below:
index.jsp
inputname.jsp
result.jsp
index.jsp :
The index page is stored in root directory "SimpleHelloByEnteringName". The code for
"index.jsp" is :<html>
<body>
<jsp:forward page="/pages/inputname.jsf" />
</body>
</html>
Description :
As you can see in code above, this page simply forwards the user to the page
"inputname.jsp" through <jsp:forward page="/pages/inputname.jsf" /> line of code. Index
page doesn't display anything to the user so you can leave creating this page but it has
one benefit that you can start application simply mentioning the application name and not
specifying any file name at the end of URL i.e. we can simply write
http://localhost:8080/SimpleHelloByEnteringName in the URL and see output of the
application.
So the first page that appears to the user is "inputname.jsp" not "index.jsp". The code for
"inputname.jsp" is:
<f:view>
<html>
<head><title>enter your name page</title></head>
<body>
<h:form>
<h1><h:outputText value="#{message.inputname_header}"/></h1>
<h:outputText value="#{message.prompt}"/>
<h:inputText value="#{StoreNameBean.personName}" />
<h:commandButton action="result" value="#{message.button_text}" />
</h:form>
</body>
</html>
</f:view>
Description :
With taglib directive we include the JSF tag libraries. First line tells where to find JSF
html tags that defines html elements and second line tells where to find JSF core tags. A
page which contains JSF tags is represented by a tree of components. The root of this tree
is UIViewRoot. This root is represented by view tag. So it is necessary to include all
component tags (tags representing UI components) within view tag.
This line loads our properties file (resource bundle) that holds messages that we want to
display in our JSP page. Actually this file is a collection of param=value pair. The name
of this file is "messages.properties" in this application which is saved in
/WEB-INF/classes/roseindia folder. We will explain more about this in subsequent
section.
<h:form>
This tag creates html form using JSF tag. Typically JSP page includes a form, which is
submitted when a button is clicked. Form components must be nested inside the form tag
i.e. within <h:form> and </h:form>.
<h:outputText value="#{message.inputname_header}"/>
This tag looks into the resource bundle i.e. properties file(messages.properties) . It looks
the value for inputname_header parameter in "message.properties" file and set the value
of it to value attribute. Finally this tag prints this value. So in this example this line prints
"Roseindia JSF Tutorial".
<h:outputText value="#{message.prompt}"/>
In this line the value of "prompt" param is looked in "messages.properties" file and this
tag prints this message. So in this example this line prints "Enter Your Name:".
This tag is used to create input text box component. The value attribute is used to connect
this field to the managed bean attribute .Here StoreNameBean is the name of Bean and
personName is the name of attribute of bean. After pressing the submit button bean gets
the value in the input text box filled by user . This bean is nothing but a Java Bean that
contains attributes and setter and getter methods to set and get those attributes. We will
explain more about Managed Bean later in this section.
This tag represents command button component. Here again the value attribute gets its
value from "messages.properties" file. So in this example this line prints "Submit" on
button component .The action attribute is used to see which page will be displayed next
when we will press this button. This "result" value is matched in faces-config.xml file in
WEB-INF folder where navigation rules are defined. How to define navigation rules in
faces-config.xml file will be described later in this section. Here in this application the
next page is "result.jsp" when submit button is pressed..
The collective output of tags used in inputname.jsp page will give rise to the first page
appeared in front of the user: So the output of the page is given below:
When above page appears to the user, user enters name to the input text field and submits
the button, a new page "result.jsp" is generated that welcomes the user with the user
name. The code for "result.jsp" is :
<f:view>
<html>
<head><title>enter your name page</title></head>
<body>
<h:form>
<h1><h:outputText value="#{message.inputname_header}"/></h1>
<h:outputText value="#{message.prompt}"/>
<h:inputText value="#{StoreNameBean.personName}" />
<h:commandButton action="result" value="#{message.button_text}" />
</h:form>
</body>
</html>
</f:view>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:loadBundle basename="roseindia.messages" var="message"/>
<html>
<head>
<title>greeting page</title>
</head>
<body>
<f:view>
<h3><h:outputText value="Hi, #{StoreNameBean.personName}!" />
<br/><h:outputText value="#{message.greeting_text}" />
</h3>
</f:view>
</body>
</html>
Description :
First three lines are same as in "inputname.jsp" file.
<h:outputText value="Hi, #{StoreNameBean.personName}!" />
This line is used to access the value of personName attribute from Java Bean named
"StoreNameBean" and prints this value(i.e. person's name) on the page.
<h:outputText value="#{message.greeting_text}" />
This line looks the value of greeting_text in "message.prorerties" file and prints this value
to the page. Here this line prints "Welcome In Roseindia JSF Tutorial".
Output of result.jsp :
So output will be like this (if "rose" is entered in the text field of "inputname.jsp" file):
Now we come to those topics that has been left unexplained above.
In above JSP files we have used "message.properties" file. This is a properties file and is
a collection of param=value pairs. We can use there values of param in our JSP file as we
did it previously. This provides a great benefit to the application like we can modify these
values easily and there is no need to change the JSP file. In this application we have
created "messages.properties" file in roseindia folder in WEB-INF/classes folder. The
code for this file is:inputname_header=Roseindia JSF Tutorial
prompt=Enter Your Name:
greeting_text=Welcome In Roseindia JSF Tutorial
button_text=Submit
In the above JSP files we have used Managed Bean named "StoreNameBean". For this
we have created "PersonBean.java" file. This Managed Bean is nothing but a Java Bean
that contains attributes and setter and getter methods to set and get those attributes. Here
in this example there is only one attribute named "personName" and so only one setter
method setPersonName() and one getter method getPersonName() for that attribute. This
bean is used to get values entered by user after submit button is pressed. Make sure the
attribute in this class must be same as the field name in JSP. In this example this file is
created in package roseindia. So compile this file and place its class file i.e.
PersonBean.class in roseindia folder in WEB-INF\classes folder. The code for this class
is:
package roseindia;
String personName;
If you want to access the bean classes in your JSP files, you have to register the bean
classes in faces-config.xml. So now its turn to declare this bean in configuration file
faces-config.xml that has been described in the next section below:
We have already created faces-config.xml file with empty <faces-config> tag. This
configuration file is used to register managed beans, specifying navigation rules etc. We
will add <managed-bean> element within <faces-config> and </managed-bean> tag to
register Managed Bean. So this registration code will be like this for this application:
<managed-bean>
<managed-bean-name>StoreNameBean</managed-bean-name>
<managed-bean-class>roseindia.PersonBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
Now we will understand how navigation from one page to the next page is performed as
in our application inputname.jsp page navigates to result.jsp page when user presses
submit button after filling text in input text field. To understand this we come back to the
the line of code used in "inputname.jsp":
<h:commandButton action="result" value="#{message.button_text}" />
Here action attribute is set to "result". When user presses the command button then which
page will be displayed is determined by the navigation rule defined in faces-config.xml
configuration file. This rule has been defined like this for our application :
<navigation-rule>
<from-view-id>/pages/inputname.jsp</from-view-id>
<navigation-case>
<from-outcome>result</from-outcome>
<to-view-id>result.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule> defines navigation rule. <from-view-id> is used to specify the jsp file
for which navigation rule is to be defined. So here we write the name of the JSP file for
which the we are defining the navigation rule. Here in our application it is inputname.jsp
that is in pages package.<navigation-case> specifies the value which is matched with the
value specified in action attribute of commandButton tag. If it matches then the page
specified within <to-view-id> tag is displayed. Here in our application it is "result.jsp".
<?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>
<managed-bean>
<managed-bean-name>StoreNameBean</managed-bean-name>
<managed-bean-class>roseindia.PersonBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<navigation-rule>
<from-view-id>/pages/inputname.jsp</from-view-id>
<navigation-case>
<from-outcome>result</from-outcome>
<to-view-id>result.jsp</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
Editing web.xml :
The FacesServlet servlet works as an engine for all JSF applications. So as we are using
JSF framework in our web application, we will edit the deployment descriptor file
web.xml to define "FaceServlet" and its mapping in web.xml file.
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup> 1 </load-on-startup>
</servlet>
The FacesServlet servlet works as an engine for all JSF applications( handling of all JSF
related requests, building component tree of the JSP page, accessing all JSP pages in the
application, creating an Event object and passing it to any registered listener). So all
requests that need FacesServlet processing must be directed to this servlet. So if we want
to invoke this servlet with every request we have to do mapping in <servlet-mapping>
element. This is done to map a particular URL pattern with the Faces servlet. URL of
every request must contain <file name>.jsf pattern because we have mentioned this
pattern in <url-pattern> tag.
If we look in "index.jsp" file, we will find that there is .jsf file suffix not .jsp in the path
for the forward.
<jsp:forward page="/pages/inputname.jsf" />
This is done to map a particular URL pattern with the Faces servlet. This is used here
because we have used *.jsf in the URL pattern in the web.xml file for the application.
This is used to signal that the forwarded page should be handled by the FacesServlet
servlet within Tomcat.
JAVA SERVER FACES ( not to be confused with JSP..JAVA SERVER PAGES), is the
latest technolgy from JCP(Java Community Process).
It is a technology that can be used instead of Struts or along with Struts,during the
transition phase. In this three part tutorial, the author gives the salient features of the
technology with a simple illustration.
---------
Craig MacLanahan, employed in SUN and the main contributor behind Struts , is the
lead architect of JSF. He maintains that JSF is a supporting technolgy for Struts and not
necessarily a replacing technology. He himself has suggested a method of integrating
Struts with JSF and getting the best of both worlds.
( As this tutorial presumes a foundation in Struts, readers will do well to refer to the
tutorial on Struts in DeveloperIQ..Jan2005).
However, many analysts and authors are of the opinion that JSF is a definite
improvement over Struts.Thus, it may be expected that quite a few applications in
Industry , presently using Struts may switch over to JSF in the near future. In a few
special cases, combining both JSF & Struts may be attempted, in order to maintain
backward compatibility, during the transition phase.What is worth noting is that,
transition is inevitable.
From the view-point of productivity, builder tools are preferred by the Industry.
For example, though, we can build very elegant and powerful applications in ASP.net ,
by using only a text-editor , Industry prefers to use Visual Studio , because of the
number of advanced features like 'Intelli-sense', class browser etc.Similarly, while a
considerable number of programmers prefer to use nothing but JDK and related libraries
with text-editors , however complex the code might be,equally numerous programmers
prefer to use the visual tools like JBuilder, JDeveloper and IBM's WebSphere Studio.
The only problem is that while JDK is a single entity and hopefully can be mastered,
builder tools are numerous and one cannot be equally productive in all the tools. Thus,
anyone , who makes extensive use of such tools in his work, gets habitually tied to that
tool and becomes much less productive in another environment. And for students and
job-seekers, this poses a problem , since, with all their proficiency is a particular builer-
tool like '(say) Eclipse, the employer may be a fan of some other tool such as
'JDeveloper'.
Such a problem does not occur in Microsoft Visual Studio, because there is one and only
Studio. But even in Microsoft IDE, there are
possibilities for working in various types of projects. Even the VC++ studio, offers
options for console mode,win32 apps,Wizard-based dialog mode, SDI , MDI etc.Thus ,
if we want, we can develop our program without using wizards and code-generators
thereby greatly reducing the number of files and code-bloat.
That said, Industry is not prepared to forego the enormous increase in productivity
offered by these tools. Thus learners have to master atleast two or three leading Java-IDE
environments besides the plain JDK, to feel at home in Industrial environment and trust
their luck to land in a java shop that uses an IDE known to them! That pinpoints the
necessity for standards.JSF is such a standard.
JSF is a specification, to which big companies like Borland , WebLogic, Oracle, SUN
etc can offer Studio like tools to enhance productivity. And , they have already adopted
and introduced JSF in their tools. Added to this is the advantage that it comes from JCP
and that settles the issue, for good! .Hence JSF is inescapable area of expertise for Java
developers.
Just as we can build asp.net pages by hand-coding, we can build JSF also by hand-
coding. But , the main advantage as perceived by many analysts is that JSF being a
specification, it has created a common standard for Visual Builder tools for web-
application development in Java. As it is backed by all the big players, it is bound to gain
momentum and universal acceptance quickly.
The problems that are addressed by Struts are different from those addressed by JSF.
Struts is a framework based on MVC and it provides a ready-made structure, the main
advantage being, DECLARATIVE MANAGEMENT in two important files, namely,
web.xml and struts-config.xml. Secondly, it provides the concept of form-beans and
centralized flow through the Controller servlet and respective action classes. It separates
the view (JSP) and the model (business logic).It has been widely adopted by the industry
and has proved its worth.
Why then, JSF? Unlike Struts, JSF is not a web-application framework but was intended
primarily, to be a User-interface technology, for web-based applications. In this aspect, it
is exactly like ASP.net's WebForms.However, it soon grew out of this constraint and
overlapped with much functionality and architecture of Struts.
-------
Let there be a form with two text boxes and a button. When the user types his name in
text1 and clicks the button, it should appear in text2.
text2.text=text1.text
Had this been a stand-alone Java program, the code would have been,
text2.setText(text1.getText());
-------------------
In desktop applications, the variables are readily available in the program's memory
space. But in web applications, HTTP is used and it is state-less. So, we can only collect
the data typed in text1, in the server-side.
After this , we have to dynamically create the same gui as before and populate the two
textboxes, in the client's browser,and send the button too! Struts solves this problem, by
creating a form-bean ..It would be nice if java web-application developers are 'made to
feel' that they are working in a Swing based Applet , instead of web-based html form
with all its 'forgetfulness'!That is precisely the problem tackled by JSF.
For all appearances, it is as if the program works as in desktop application, where when
we click a button(ActionEvent), make a change in textbox(TextEvent),make a selection
in combo(ItemEvent),there is a reaction at component level .Struts, for all its advanced
features, lacks this, as it is a page-level technology.
Or if we prefer, we can think of a Java desktop program, JSP ( either plain,or MVC or
Struts) and JSF.If we combine the features of VB & ASP, we get ASP.net. (we are
speaking here of how it 'appears' to the developer, and not as it is
implemented!).Similarly, when we combine Desktop Java & Struts, we get JSF.
Clearly then , JSF is an advance over Struts, with the added advantage of being an official
JCP standard, unlike Struts.
About ten years back(1995), users were captivated by the tremendous reach and ease of
Web-based applications. They used to call those start-ups as 'click & barter' company in
the place of 'brick & mortar' company. Even today, there are hugely successful
e-commerce companies like Amazon.com. So, the web-based business model is here to
stay and grow. There is no going back to narrow lan(e)s of pre-web days.
But, as business grows, developers and users alike, want to have all the ease, color,
variety and user-interaction of a desktop application like VB ,in a web-based form!
Surprisingly, was it not offered by Java Applet, in its very first month? But, it was
objected that the business logic was done by the applet in the client's browser and except
for very simple applications, downloading all those heavy classes from the server into
the client's browser is not at all a good solution.
Later, Sun came out with Servlets solution, in which the business logic is executed either
in web-server or in the next tier of application server(RMI-style).And it is possible to
send data to the servlet , not through the html form but through an applet.(They used to
call it Applet-Servlet Communication and Tunnel method).
If that is the case, the rich user-interface of applets can be combined with the power of a
servlet and since the applet is used only for attractive user-interface and quick user-
interaction, there could be no objection. The client's machine need not have JDK
installed. The applet can be downloaded from server. This approach had an added
advantage too. By suitable relaxation of security policy, data can be extracted from the
hard-disk of the user by the applet and sent to the servlet. Similarly, the result sent by the
servlet to the applet can be stored in the user's hard disk.Thus, we can save the data in a
textbox to the file in hard disk, elegantly.That is the power of Component approach over
page approach.
Though, the first wave of books and literature on Servlets (1999)always spoke about
servlet-applet communication, it fell out of favor, possibly due to the rift between
Microsoft and Sun for fear that the almost universal Internet Browser and even Netscape
Navigator, did not implement JDK fully in those days. And Swing is not implemented in
these browsers directly , even today. It is only by using Java plug-in from Sun, we can
view Swing applets in browsers.In J2EE field, where innovations and changes are
occuring almost every month, a timelag of half a decade is equivalent to 'anachronism'.
There is not much use in connecting a servlet through a stand-alone frame. We cannot go
about distributing the client-side classes to the users.Only if it could be downloaded from
the server, it can serve a vast clientele.It is signigicant that the Applet technology has no
equivalent in Microsoft technologies, to this day! Applets do not get installed in the user's
machine but if AciveX controls embedded in html were downloaded , they got registered
in the Windows Registry.
ActiveX Documents tried by Microsoft , were not html forms and so could not be a
standard method. That is what led them to develop ASP.net web forms.(please refer to a
tutorial on ASP.net in DeveloperIQ...Feb --2004).But, still, the web-form controls are
not the same as windows-form controls. DataGrid of windows-forms in Dotnet and
DataGrid in Web-forms , will show this difference.Thus, it would appear that if it were
possible to ressurect the Applet-Servlet approach, it would be incomparable, in effect.
Now that Sun & Microsoft have buried the hatchet and agreed to co-operate for the
coming decade, it will not be too much to expect Microsoft to implement jdk fully in its
browser, atleast so far as Swing GUI goes. If that happens, we can combine all the
advanced gui features of Swing applets with the power of Servlets/JSP. .
In the absence of response to this wish-list, the next best solution is to create controls in
server-side and somehow send it to the browser, as html. That is what is being done by
ASP.net & JSF.
Round trip to the server is inevitable in a web application. True! But, the technolgy
should hide all that complexity and make the coder feel that he is developing a desktop
application. This is the chief merit of ASP.net's WebForm and also that of JSF.
How then does JSF differ from ASP.net? There is no concept of Declarative management
in ASP.net, exactly matching that in JSF. But the plus point of ASP.net webforms is that
naming of the tags is much like standard html tags ( or VB) and elegant, unlike the JSF
tags.Many more comparisons could be made but the main thrust of this tutorial is getting
acquainted with JSF and so such a comparative evaluation, will have to wait. It is well to
remember that there is no place for Talibanism in Technology!Discerning observers can
easily see how each camp is learning from the other and trying to do one better.That is
how progress takes place.
Just because, we said that JSF is primarily a GUI technology for web-applications, it
should not be taken to mean that it does away with all that concern about MVC
Architecture.
That would have been a step back, after so much work that has been done to achieve
separation of Model,Controller & View. Thus, JSF adopts quite a few features from
Struts. For example, here also there is a central controller servlet , only, it is named Faces
Servlet. Here also, we have, a configuaration-file like Struts-config.xml, but it is now
faces-config.xml
Decalative navigation method also has been adopted. Just as in Struts, the code simply
returns 'Success' or 'Failure' and the resulting forwarding is decided declaratively by
Navigation rules in the xml file. Internationalization, Error messages, Validations, beans
for holding data, model beans etc are all very much in the same style of Struts.
We have custom tags in JSF too.( And these tags may not always be compatible with
JSTL!). ... And many of these html tags had no equivalent in JSTL. There is overlapping
functionality and nomenclature between JSF tags and Struts tags. While, Struts used JSP
EL(Expression language), JSF uses JSF EL!
Thus, JSF may be looked at as an 'improved' Struts . Many authors feel that JSF is easier
to implement and richer in user-functionality,but Struts validation is said to be much
better. However,things could improve in the coming months.
While Struts is strongly tied to standard browsers, JSF caters to all kinds of emerging
browsers like wap-browsers and wireless devices, just like ASP.net. As wireless is the
emerging trend, this also is a progressive step in JSF.At the pace in which wireless
communication infrastructure and technologies are being developed all over the world,
purely desktop wizardry has no value atall, in future. The real challenge is to develop a
web-application with the look and feel of the desktop application!It takes some effort to
effect this change in approach.
What JSF brings to the party is ,the direct Event model , like Swing's Action event and
ActionListeners,a concept like Container for controls in Swing, etc.
In the second part of the tutorial, we will learn JSF fundamentals by experimentation,
intermixed with brief theoretical notes, where needed.
In this second part of the tutorial, the author explains the practical steps to get our first
few demos in JSF, running. Basic theory behind the steps also are given.
We are using Tomcat-5 as the Web-server,along with JDK 1.4.2, for the following
experimental work.
First of all , we have to instal JSF package in our system.We downloaded JSF1.1 , from :
http://java.sun.com/j2ee/javaserverfaces/download.html
a) docs
b) javadocs
c) lib
d) metadata
e) renderkitdocs
f) samples
g) tlddocs
The samples folder is useful to get started. There are four sample demos in that folder as
*.war files.
i) jsf-cardemo.war
ii) jsf-components.war
iii) jsf-guessNumber.war
iv) jsf-nonjsp.war
Of these four, jsf-gueessNumber demo has minimum features , and is best suited for
getting a feel for the technology.So, we copied jsf-guessNumber.war to :
----------------------------
>e:\tomcat5\bin
>set JAVA_HOME=e:\jdk1.4.2
>startup
----------------------------
The war file gets expanded automatically and we get the standard j2ee directory
structure, inside the
..\webapps\jsf-gussNumber\WEB-INF\classes
..\webapps\jsf-guessNumber\WEB-INF\lib
All the jar files needed for running the jsf program are present in ,
i) commons-beanutils.jar
ii) commons-collections.jar
iii) commons-digester.jar
iv) commons-logging.jar
v) jsf-api.jar
vi) jsf-impl.jar
vii) jstl.jar
viii) standard.jar
It is useful to note down these details so that we can easily follow the documentation ,
articles and books, later.
Let us see the significance of these jar files now. ( refer to page: 118 of JSF by Dudney).
1)jsf-api.jar : contains the standard JSF API classes and interfaces that all JSF
implementations must satisfy.
2) jsf-ri.jar : represents the Sun Reference implementation of JSF API.
3) jstl.jar & standard.jar contain the JSTL files. The Reference implementation is based
on JSTL.
'commons' utilities are being mentioned by many experts as invaluable library for fast
software development. It will be dealt with in detail in a forthcoming tutorial.
'http://localhost:8080/jsf-guessNumber/index.jsp'
we will get textbox and a button along with the image of Sun's mascot, the 'Duke'..We
will be asked to type a number between 0 & 10.If we type a character like 'a' and submit ,
we will get validation error message in red. If we type a 'wrong' guess, we are informed
so. After a few trials, we get correct result. Nothing much. But,it shows that JSF is
working in our system and we get ready to begin our experimenation.!
The Struts application comes with struts-blank.war and it is renamed to our application
name . It would have been better if the JSF distribution also came with such a skeleton
application. But , there is no such demo and that is why we are using the guessNumber
folder , so that we get the standard xml files, required for our application. If we type it
from scratch, there will be typing errors and difficulties. The best thing is to rename jsf-
guessNumber folder as ,(say) 'ourdemo'.
We now delete all the jsp files directly under 'ourdemo' folder.We delete all the class files
under 'WEB-INF\classes' of 'ourdemo', because they are applicable to guessNumber app
only.Retain all the jar files in lib folder under WEB-INF.
a) web.xml
b) faces-config.xml
----------------------------------------
// \webapps\ourdemo\WEB-INF\faces-config.xml
<?xml version='1.0' encoding='UTF-8'?>
"http://java.sun.com/dtd/
web-facesconfig_1_1.dtd">
<faces-config>
<application>
<locale-config>
<default-locale>en</default-locale>
</locale-config>
</application>
<navigation-rule>
<description>
</description>
</navigation-rule>
</faces-config>
---------------------------------------------
-----------------------------------
//..tomcat5\weebapps\ourdemo\mathew.jsp
<html>
<body>
I AM MATHEW
<br>
</body>
</html>
--------------------------------------
'I AM MATHEW'.
----
We now create a simple JSF program to learn about the tag library of JSF.
-----------------------
// tomcat5\webapps\ourdemo\jsfgui.jsp
<f:view>
<html>
<body bgcolor="cyan">
</h:form>
</body>
</html>
</f:view>
--------------
================================
But , we should learn something about two important xml files, before we proceed
further.
This file was obtained by deleting comments and descriptions from the original web.xml
file of guessNumber application, to serve as a model, to make it less cluttered. This basic
model file can then be used for other applications. In all the applications, the web.xml file
will be same! (just as the web.xml file was same in all the Struts examples). But we
should carefully note that the name of the central controller servlet and its URL-pattern.
---------------------------------------
// ..\webapps\ourdemo\WEB-INF\web.xml
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>trial</display-name>
<description>
</description>
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<context-param>
<param-name>com.sun.faces.validateXml
</param-name>
<param-value>true</param-value>
<description>
</description>
</context-param>
<context-param>
<param-name>com.sun.faces.verifyObjects</param-name>
<param-value>true</param-value>
<description>
</description>
</context-param>
<servlet>
<servlet-class>javax.faces.webapp.FacesServlet
</servlet-class>
<load-on-startup> 1 </load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet
</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>
faces/login.jsp
</welcome-file>
</welcome-file-list>
</web-app>
============================================
In the servlet-mapping tag, we can make use of two styles of url-pattern. The first style is
known as 'extension mapping'.
( example: *.jsf). The JSF specification recommends the use of 'faces' as the extension
but we can also use *.jsf.
----------------------------------------
(EX)
< http://localhost:8080/demo/index.jsf>
or
< http://localhost:8080/demo/index.faces>
<http://localhost:8080/demo/index.jsp>
----------------------------------------
---------------------------------------
(example)
<url-pattern>/faces/*</url-pattern>
(ex)
http://localhost:8080/demo/faces/
http://localhost:8080/demo/faces/index.jsp
===========================================
The state of the various controls can be saved either in the server-side or in the client-
side. We have specified 'client' as the option. This is saved as 'viewstate'.
If we have a sense of 'deja vu', it is because , the same technique is used in ASP.net too!
---
Next we should learn the basics of another important xml file . Just as we had the struts-
config.xml file, here too we have faces-config.xml file.
This file has the following child-elements: The order in which these elements occur is
important and should be retained.
1) application:
2) factory:
3) component:
4) converter:
5) managed-bean
6) navigation-rule:
7) reference-bean:
8) render-kit:
9) lifecycle:
10) validator:
----
For the usual applications, it is advisable to accept the defaults for most of these. Since
'zero' entries are permitted for all these child elements, we can just remove many of them.
The items shown in 'bold' such as managed-bean, navigation-rule are the most needed
items.
However, for the jsfgui.jsp, these are not needed. So the skeleton faces-config.xml will
appear as shown earlier to begin with.
--------------------------------------------
So, we are able to get started with the tags in JSF. The names of these tags are
unfortunately , a bit contrived and confusing.
--------------------------------------------
-------------------------------------------
Inside the body tag, we must always provide <view> tag. This is very important. All jsf
The <view> tag provides a place for saving the state of the components tree before
sending the response. If we have configured to save it in client, it is returned as 'hidden'
viewstate , just as in ASP.net.
We will now see a few jsf tags and the html equivalents.
------------------------------------------
1) <h:form> <form>
2) <h:outputText>
3) <h:inputText> type=text
4) <h:commandButton> type=submit
5) <h:inputSecret> type=password
6) <h:panelGrid> table
7) <h:graphicImage> img
8) <h:message>
9) <h:selectOneRadio> <radio>
15) <h:message>
In this third part of tutorial on JSF, the author deals with important topics like 'backing
beans',event-handling,validation etc.
While the first part of this tutorial dealt with the overall perspective and the need for
JSF,the second part gave the practical steps required for installation, preliminary testing
and basic trial for our own example.In this third part , we will have a deeper study of the
essential ingredients of the JSF architecture ,backed up with simple illustration for each
of those ingredients.
(Manning/DreamTech) published in Jan 2005, KITO MANN, has given an outline of the
various component parts of the JSF, as follows.
i) UI components & JSF Tag library
ii) Navigation
iii) Event-handling
v) value-binding
vi) method-binding
vii) validation
viii) converters
-----------------------------------
1) Security
2) tabular data
4) Internationalization
---------------------------------------
We have already seen the basics of JSF tags.In our next demo, we will study the details
about 'Navigation'. This requires some suitable entries in faces-config.xml file.
-- ---------------------------------------
//jsfevent.jsp
<f:view>
<html>
<body bgcolor="cyan">
</h:form>
</body>
</html>
</f:view>
---------------------------------------------
<html>
<body>
I AM MATHEW
</body>
</html>
--------------------------------------------
// e:\tomcat5\webapps\ourdemo\amy.jsp
<html>
<body>
I AM AMY
<br>
</body>
</html>
--------------
Now, we have to make the following entries in faces-config.xml
// e:\tomcat5\webapps\
ourdemo\WEB-INF\faces-config.xml
<navigation-rule>
<from-view-id>
/jsfevent.jsp
</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/mathew.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>failure</from-outcome>
<to-view-id>/amy.jsp</to-view-id>
</navigation-case>
</navigation-rule>
------------------------------------------
and restart tomcat server
------------------------------------------
faces/jsfgui.jsp'
We will get just two buttons.One button will have the caption as 'mathew' and the other
button's caption will be 'amy'. If we click button1,we will be taken to mathew.jsp and if
we click button2 , we will be taken to amy.jsp, with corresponding displays. Thus, we
have given a demo for action event as well as 'Declarative navigation'.
We say,this is declarative navigation, because, the outcome of clicking 'button1' has not
been hard-coded but simply mentioned as a string "success" in the button's action
attribute.
What this 'string' should do, has been indicated in the jsf-config.xml under navigation
rule attributes., as shown below.
-------
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/mathew.jsp</to-view-id>
</navigation-case>
---------
This is very much similar to the practice in Struts. Similarly, for button2 ( with caption
'amy'), the action attribute is 'failuree' and in the faces-config.xml, we have mapped it to
'amy.jsp'.
Hopefully, this illustration explains the method of action event, navigation rule syntax
and princople of declarative navigation.
******************************************
Now, we take up the MOST IMPORTANT topic of BackingBean. Though the name is
unique, it is just nothing but the standard javabean.
f:\>md jsfexample
f:\>cd jsfexample
f:\jsfexample>md demo
f:\jsfexample\demo\>edit player.java
( it may be noted that the name of the working folder NEED NOT BE the same name as
the package name! Our working folder is 'demo' but the package name is ourdemo).
( The package name has nothing to do with the Application context name either, though it
is followed by Sun demos.)
---------------------------------------
// f:\jsfexample\demo\>player.java
package ourdemo;
import javax.faces.context.*;
import javax.faces.component.*;
import javax.faces.validator.*;
String firstname;
String lastname;
firstname=a;
return firstname;
//----------
{
lastname=b;
return lastname;
//-------------------
====
f:\jsfexample\demo>
set path=c:\windows\command;e:=\jdk1.4.2\bin
demo>set
classpath=j:\jsfexample;
f:\jsf11\lib\jsf-api.jar
---------
The player.class file thus obtained must be copied to 'ourdemo' folder under :
e:\tomcat5\webapps\ourdemo\WEB-INF\classes
-----
edit \webapps\ourdemo\jsfmbean.jsp
-----------------------------------------
//jsfmbean.jsp
<f:view>
<html>
<body bgcolor="cyan">
</h:form>
</body>
</html>
</f:view>
=============================================
<navigation-rule>
<from-view-id>/jsfmbean.jsp</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/mathew.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<managed-bean>
<managed-bean-name>player</managed-bean-name>
<managed-bean-class>
ourdemo.player
</managed-bean-class>
<managed-bean-scope>
session
</managed-bean-scope>
<managed-property>
<property-name>firstname</property-name>
<value>Mahathma</value>
</managed-property>
<managed-property>
<property-name>lastname</property-name>
<value>Gandhiji</value>
</managed-property>
</managed-bean>
==============
http://localhost:8080/ourdemo/faces/jsfmbean.jsp
---------------------------------------
We will get two textboxes and two buttons. We will get the value 'Gandhiji' bound in the
second textbox.There will be no entry in text1; This is known as 'Value Binding'. What
do we mean by that? As we know, the player bean class has two attributes namely, 'first
name ' and 'last name'.
We have specified in the jsf-config.xml file the init value for these two attributes. In the
jsp sheet we have mentioned that the value of text2 is "#{player.lastname}".
(This is very much similar to JSP EL. But, it is not totally compatible with JST EL).
Thus the value of the bean is bound to text2. This is a two-way process. Hereafter, if
either the bean's attribute is changed by code or by the user changing the value in the
screen, the inner vvalue is changed, each time the page is submitted. The value is retained
( sticky) so long as the page's session is maintained. This is a very important feature and
almost the most important feature in JSF.
---------------------------------------------
There is another method of binding also. This is very unique in JSF, not found in Struts.
This is known as 'method binding'. Our player bean has a method known as
'changeName'.
When the button 'success' is clicked we will be transfered to mathew.jsp. When the
button 'failure' is clicked we will get 'Mahathma Gandhiji' in textbox2. This is an example
for method binding. This result is obtained from the 'changeName' method of the bean.
---------------------------------------
Next we will move on to another important part(ie) 'Validation'. JSF provides three
standard validator classes
1.DoubleRange Validator
This tag validates whether the submited value lies in the specified floating point range. A
minimum value, a maximum value or both may be specified.
2.Length Validator
This tag validates the length of the submitted string value and that its length is within the
supplied minimum and maximum values.
3.LongRange Validator
This tag validates whether the submitted value can be converted to a long and that it is
within the supplied minimum and maximum values.
--------------------------------------
//jsfvalidation.jsp
<f:view>
<html>
<body bgcolor="cyan">
<br>
</h:inputText>
</h:inputText>
</h:inputText>
</h:form>
</body>
</html>
</f:view>
---------
Open IE and type the URL as http://localhost:8080/ourdemo/faces/jspvalidation.jsp
We will get three labels and three textboxes. Type the value 'sam' in textbox1, 10000 in
textbox2 and 19.99 in textbox3 and click the button 'Click Me'. We won't get any error
message.When the button is clicked, the page is submitted to the server.
When we leave any textbox empty, we'll get the error message as 'value is required'. Type
the value 'thomas' in textbox1 and click submit. We will get the error message 'value is
greater than allowable maximum of '5''. When we type some characters in textbox2 and
textbox3, we will get the error message as 'value is of the correct type '. When we type
the numbers out of range in textbox2 and textbox3, we will get the error message
'Specified attribute is not between the expected values'.
*******************************************
Reference Books:
- Kito D.Mann
(SPD/OReilly/june 2004)
- Bill Dudney
( Wiley/DreamTech/2004)
In this first part of the tutorial, Ms.Noushene, explores the examples provided by SUN, in
the JSF package.
The JSF1.1 can be downloaded form :
<http://java.sun.com/j2ee/javaserverfaces/
download.html>
The jsf1.1 package has various interesting examples. Let us explore them and study the
various GUI components , provided by SUN,in the first part of this tutorial.
First copy jsf-components.war and jsf-nonjsp.war from samples folder of jsf1.1 to the
webapps folder of tomcat5. Next start tomcat5 server with JAVA_HOME as jdk1.5. (*
Some examples will not run properly when jdk1.4 or jdk1.4.2 is used.)
1. Image Map
2. Menu or Tree
3. Repeater
4. Scroller
5. Tabbed Pane
6. Chart
Fig. jsf-mainform screenshot
Each example has a JSP and a number of java classes(beans) used by the JSP. Let us
consider each example now one by one.
1. Image Map:
When the link ‘execute JSP’ corresponding to image map demo is clicked, we will get a
world Map. When we move the cursor over a particular country, it gets colored. A
number of world maps, a plain map and colored maps (map with a colored country) is
present in images folder of jsf-components. In this, the image is added by using the tag
<h:graphicImage> and each country is given a different id and value by using the tag
<d:area> and the attribute ‘onmouseover’ is used to change the maps when cursor is
passed over a particular country.
Fig: jsf-screenshot-1 Image Map
2. Menu or Tree:
When the link ‘execute JSP’ is clicked, we will get menus and trees. The tag
<d:graph_menubar> is used to place menubar component and <d:graph_menunode>
corresponds to an item on the menu node. Similarly <d:graph_menutree> tag consists of
multiple graph_treenode tags. Each <d:graph_treenode> tag corresponds to a node in the
tree, and we can nest <d:graph_treenode> tags within each other.
Fig. jsf-screenshot-2 (Menu and Tree)
The tree and menu controls can be added by using the model or JSP tags. JSP tags are
very easy to use and we can develop simple programs in the next part of this tutorial.
When we use JSP tags we need not write any bean and no need to make any entries in the
faces-config.xml file.
a) selectedClass:- A style sheet class which controls the display attributes of the selected
menu bar or tree element. This is used to distinguish the selected portion from the other
unselected portions.
3. Repeater:
In ASP.net we have datagrid control with provision for visual manipulation of data rows
or records. We can add, update or delete data in a row visually without writing SQL
code.The JSF Repeater is a similar control.
When we run the repeater program, we will get a Customer List. It consists of
checkboxes, textboxes for Account-Id, Customer Name, Symbol, buttons with account
No a link and a number of buttons to create new row, delete checked row, to show first or
last page, next or previous page, and to reset or save changes.
When we press any button we will get corresponding messages and the corresponding
changes are made. Evidently, this will be the most valuable control in practical work.
4. Scroller:
In our email programs, we get a lot of pages each page containing about ten mail
references. We have , provision for going from one page to the next ( next/previous). The
Scroller control does one better! We can directly jump to any desired page. This is very
useful control.
Fig. jsf-screenshot-4 (Scroller)
5. Tabbed Pane:
When we run the tabbed pane program we will get three tabbed panes.
Fig. see jsf-screenshot-5(Tabbed Pan).
The tags <d:pane_tabbed> and <d:pane_tab> are used to place a tabbed pane. The
procedure to develop simple tabbed panes is shown in the next part of this tutorial.
6. Chart:
When we run the Chart program we will get a vertical bar chart, a horizontal bar chart
and a pie chart.
Fig. jsf-screenshot-6(Chart)
The tag <d:chart> is used to place a chart. The program to develop three types of charts is
shown in the next part of this tutorial.
--------------------------------------------
The package jsf-nonjsf contains examples written in XUL demonstrating the usage of
different Java Server Faces components. These components are rendered by the Java
Server Faces framework and are not dependent on a JSP container.
An example for xul file is given below. For further theory we can refer to sun's
documentation
//f:\tomcat5\webapps\jsf-components\
label.xul
<page>
<window id="label">
</window>
</page>
That concludes the first part of this tutorial where we just familiarized ourselves with the
tags provided by SUN along with the java-source files used with eash tag. In the next
part of the tutorial, we will try to create our own illustrations.