Você está na página 1de 258

JSF - Java Server Faces

Java Server Faces (JSF) is a great JAVA technology in the field of web application
development. This tutorial at RoseIndia is the best place to go through JSF concepts in easy
and sequential way. This tutorial will take you through the basics of JSF to developing robust
JSF web applications. This is the complete guide to understand JSF, work flow of JSF,
benefits of JSF over existing frameworks. It is natural to think about learning and adopting
new framework while there exists some established and popular frameworks in present web
development landscape. This tutorial contains all you need to know about this new emerging
and robust technology of JAVA. It is the best combination of existing frameworks as it has
been developed by taking best features from all and leaving and removing the rest bad. You
can think about this fact that it has been developed by JCP (Java Community Process) of web
application experts 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).
An Introduction to JSF Technology

Java Server Faces or JSF for short is another new exciting technology for developing web
applications based on Java technologies. This JSF Introduction section introduces you with
cool JSF technology. In this "JSF Introduction" section you will be introduced with the JSF
technology, reasons that initiated the development of JSF and the benefits of JSF.
Why JSF?
Let's first understand the reasons that initiated the JSF project and why JSF is so hot these
days. There are reasons for development of new framework in-spite of many already existing
technologies like JSP, Servlets, Struts etc... If you have developed complex web based
applications in jsp then you must be knowing the problem faced with those technologies. Here
are the list of some of the problems faced with the previous technologies like JSP and Servlets:
• Tedious and repetitive coding
Previous technologies like JSP make programmer to do a lot of tedious and repetitive
coding.

• Directly working with HTTP request and response


Using these technologies programmers directly work with HTTP request and response
objects and manipulates the data. For example if user submits the registration form then
programmer writes the code to get the values of each element in the form into a variable
for further processing. When there is a need to retrieve the data from database and then
show on the form for editing, then in this case programmer writes the code to retrieve the
code from database and then set the values in the forms.
• Non availability of IDE
Non availability of IDE is another major drawback which affects the programmers
productivity and development cost of the projects increases.

JSF changes all that by giving intuitive framework to the developers. Furthermore, JSP is
specification and many vendors are developing their own implementations. Both free and
commercial implementations of JSF are available these days. You can choose any one of them
based on your requirement and budget.
Now a days software vendors are developing IDE for developing JSF based applications
which is another good news for the learners of JSF framework. Once you are familiar with the
core concepts of the JSF you can kick start the development of software projects using any
IDE available in the market. These changes in the programming world makes the life of
programmer much easier.
Java Server Faces is a component oriented and event driven framework for web applications.
JSF eases the development of GUI for web applications. JSF allows the programmers to work
with extensible user interfaces like buttons, text boxes, check boxes etc... Programmer writes
the code for particular event such as button clicked. This makes programming much easier and
now the there is no need to write request and response processing logic.
The quick Overview of JSF Technology
This section gives you an overview of Java Server Faces technology, which simplifies the
development of Java Based web applications. In this JSF overview section you will learn how
JSF fits into the web application development landscape.
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.

In this section "What is JSF?" you will get detailed overview of JSF technology, which is
ready to revolutionize the web application development process. JSF is complex system but
you will be highly benefited by JSF technology. For example, you can easily make rich
graphical Web application that can't be easily developed in HTML. Here we have tried to
explain the JSF in easily understandable manner so that beginner can also understand easily.
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.
JSF is based on well established Model-View-Controller (MVC) design pattern. Applications
developed using JSF frameworks are well designed and easy to maintain then any other
applications developed in JSP and Servlets.
JSF eases the development of web applications based on Java technologies. Here are some of
benefits of using JSF:
• JSF provides standard, reusable components for creating user interfaces for web
applications.
• JSF provides many tag libraries for accessing and manipulating the components.
• It automatically saves the form data and repopulates the form when it is displayed at
client side.
• JSF encapsulates the event handling and component rendering logic from
programmers, programmers just use the custom components.
• JSF is a specification and vendors can develop the implementations for JSF.
• There are many GUIs available these days to simplify the development of web based
application based on JSF framework.
JSF Components
JSF includes mainly:
1. Set of APIs to represent and manage state of components that helps server side
validation, event handling, page navigation, data conversion etc.
2. JSP custom tag library to create UI components in a view page.
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 started its journey from version 1.0 and now it has come to the latest version of JSF is 1.2.
The listing of versions released so far are :
1. JSF 1.2 (11 may 2006) - Latest release of JSF specification.
2. JSF 1.1 (27 may 2004) - Bug fix release. No specification changes. No HTML
renderkit changes.
3. JSF 1.0 (11 mar 2004) - Initial release of JSF specification.
There are many releases of 1.1 and 1.2 and these are listed below showing released date also:
1. 1.2_04 P01 (20 Mar 2007)
2. 1.2_04 (5 Mar 2007)
3. 1.2_02 (25 Aug 2006)
4. 1.2_01 (14 July 2006)
5. 1.1_02 (24 Apr 2006)
6. 1.1_01 (07 Sep 2004)
The JSF specification was developed under the Java Community Process (JCP) as JSR 127,
which released JSF 1.0 and 1.1, and JSR 252 which released JSF 1.2. The first release of JSF
is JSF 1.0 in 2004. JSF 1.0 supports servlet 2.3 and jsp 1.2. After JSF 1.0, JSF 1.1 was
released. The main purpose of this release was bug-fixing. There were no specification or
HTML renderkit changes. This version also works with same version of servlet 2.3 and jsp
1.2 as in the case of JSF 1.0.
JSF 1.1_01 release features bug fixes and performance improvements. Improvements
include compression of views serialized to the client, failover support when storing views on
the server, renderer fixes, and several other bug fixes and enhancements.It supports JDK 1.3.1
or later. Many bugs have been fixed so if your application depends on one of these bugs, it
needs to be changed.
JSF 1.2 is the latest release and it works with servlet 2.5 and jsp 2.1. If you want to run JSF
1.2 on Tomcat, you want 6.0 not 5.5. So JSF needs a web container that supports atleast
servlet 2.3 and jsp 1.2 and these are part of J2EE 1.3.
New in JSF 1.2
In this section we will go through some new features and changes in JSF 1.2 specification. JSF
1.1 was designed for JSP 1.2 and so could not take advantage of newer JSP features and JSP
could not be changed to fill the needs of JSF. This resulted in a number of new features and
changes. For ex.
1. Unified Expression Language(EL) :
Unified EL has been added to JSTL to overcome problems when integrating JSP EL with
the JSF EL.EL was used to access data objects in a simple way. It is used mainly as a
short-hand for accessing values. Later it was included in JSP 2.0 with more
functionality.When JSF was released it also needed EL.JSF and JSP each has its own
EL.The JSP EL is much flexibile to the web application developer but JSF people were
unsatisfied by the JSP EL.One of the reason was that it requires JSP engine to evaluate
expression at the appropriate time during the lifecycle, but JSP expressions are evaluated
immediately. The second reason behind it was that JSP functions could only call static
methods in TLD and they cannot be used to invoke public methods dynamically on server
side objects during lifecycle to validate data and handle component evevts.
So these were the reasons for developing such an EL that would work for both JSP and
JSF and make using JSP and JSF together easier. This new EL is called unified EL. So
this was inspired by EL used in JSTL and JSP. There is a package "el" in javax package
that represents EL.

In addition to the features already available in the JSP EL, unified EL has the following
features :
1. Deferred evaluation of expressions i.e.evaluation of the expression at the appropriate
time during the page lifecycle from JSP engine.
2. Support for expressions that can set and get values
3. Support for expressions that can invoke methods.
4. A pluggable API for resolving expressions
2. Ajax Support :
JSF framework can make things a little easier to write AJAXian JSF components.JSF
allows to map different instances of the FacesServlet with different lifecycles.For
example, one mapping for standard JSF requests and another for AJAX JSF requests.
3. New Tree Creation and Content Interweaving Model for Faces applications that use
JSP :
We can make JSF application without using any JSP page but it can also be developed
using both JSP and JSF.Using JSP makes some developers easy to handle.Sometimes
When integrated it did not respond as we expect. These problems have been resolved in
JSF 1.2.There have been made some changes in specification of the implementation of
the FacesViewHandler for JSP and JSP custom tag base class.
4. Integration with JSTL :
Using JSTL's <c:forEach> tag to contain Faces input components was one of the
problem, because JSP has no notion of a postback, it was not possible to apply the values
correctly to the nested input components on postback. Some new concepts in EL make it
possible to use this tag fully with any kind of JSF component.
5. Back Button issues and Multi Frame or Multi Window Faces Apps :
JSF have fixed the problem related to Multi Frame or Multi Window applications.The
browser back button also created some problems. These problems were because of
deficiency in the State Management API.
6. Associating a message with a particular component in the page :
Previously we could not include label of a component dynamically in an error message
for that component. Now it's possible in new JSF 1.2.It's also possible to override the
conversion or validation message that is displayed to the user on a per-instance basis.
7. Expose an application wide ResourceBundle to the EL :
<resource-bundle> element in faces-config allows listing many resource bundles that
should be exposed to the EL using the new ELResolver chain.This optimize performance
and prevent the need to create a ResourceBundle for every request.
8. Use of multiple renderKits.
9. Provide XML Schema for the config files, instead of using DTD.
10. Security enhancements for client side state saving.
11. Solve the "duplicate button press" problem.
12. The portlet related bug-fixes.
JSP 2.1 is developed under JSR-245 and JSF 1.2 is developed under JSR-252. These two
groups have experts and they are working independently but the main focus of development
was to provide more support and compatibility between these two technology that are
powerful web presentation technology so that they can be useful for each other.
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.
1. JSF is standard web user interface framework for Java.
2. Built on top of Servlet API.
3. JSF is a component framework
4. UI components are stored on the server.
5. Easy use of third party components.
6. Event driven programming model.
7. Events generated by user are handled on the server.
8. Navigation handling.
9. Can automatically synchronize UI components .
10. JSF supports multiple client devices.
11. JSF has extensible architecture.
12. International language support.
13. Extensive tool support (Sun, Oracle , IBM etc.).
14. 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.
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:

Easy creation of UI:


It makes easier to create complex UI for an applicaton using jsf tags.Its APIs are layered
directly on top of servlet APIs that enables us to use presentation technology other than
JSP,creating your own custom components and rendering output for various client devices.

Capacity to handle complexities of UI management:


It handles cleanly the complexities of UI management like input validation, component-state
management, page navigation, and event handling.

Clean separation between presentation and logic:


One of the greatest advantage of jsf is to clearly separate behaviour and presentation in an
application. JSF is based on the Model View Controller (MVC) architecture.

Shorter development cycle:


This separation between logic and presentation enables a wide range of users( from web-page
designers to component developers). It allows members of team to focus on their own work
only , resulting in division of labour and shorter development cycle.

Standard Java framework:


JSF is a Java standard which is being developed through Java Community Process (JCP).
Several prominent tool vendors are members of the group and are committed to provide easy
to use, visual, and productive develop environments for JavaServer Faces.

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.
Support for multiple client devices:
Component developers can extend the component classes to generate their own component tag
libraries to support specific client. JSF flexible and extensible architecture allows developers
to do so.

Flexible rendering model:


Renderer separates the functionality and view of the component. So we can create multiple
renderers and give them different functionality to get different appearance of the same
component for the same client or different .

International language support:


Java has excellent support for internationalization . It allows you to localize messages with
user specific locale. A locale is a combination of a country, a language, and a variant code.
JavaServer Faces adopts this property and let you specify which locale your application
supports. So you can display you messages in different languages.

Robust tool support:


There are several standard tool vendors like Sun Java Studio Creator who provide robust tools
that take advantages of JSF to create server side UI easily.
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 :

1. Simple components, like text box, button and


2. Compound components, like table, data grid .
A component containing many components inside it is called a compound component.
Components help developers to create UIs by assembling a number of components ,
associating them with object properties and event handlers. Would u like to repeat the same
code again & again and waste time if u want to create many tables in hundreds of pages in
your web application? Not at all. Once you create a component, it’s simple to drop that
component onto any JSP.

JSF allows you to create and use components of two types:


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

UIForm represents a user input form that is a container of other


components.
UICommand represents UI components like buttons, hyperlinks and menu items.
UIInput represents UI components like text input fields, numeric input fields.
2. 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 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:
1. JSF Core Tags Library and
2. JSF Html Tags Library
Even a very simple page uses tags from both libraries.
<%@ taglib uri=”http://java.sun.com/jsf/core “ prefix=”f” %>
<%@ taglib uri=”http://java.sun.com/jsf/html “ prefix=”h” %>
<f:view>
<h:form>
……………
……………
</h:form>
</f:view>

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:

Inputs (inputText, inputTextarea)


Outputs (outputText, outputLabel)
Commands (commandButton)
Selections (selectOneRadio, selectOneListbox, selectOneMenu for radio
buttons, list boxes, menu etc)
Layouts (panelGrid)
Data table (dataTable)
Errors and messages (message, messages)

Some examples have been given below to understand how to use these tags and its
attributes:
<h:inputText id=”ID1” value=”value”/>
creates a single line text input control where id attribute is used to uniquely identify
the component rendered by this tag and value attribute sets the current value of the
component.
<h:outputText id="ID2" value="Welcome"/>
creates a single line text output where id attribute uniquely identifies the rendered
component and current value is set by value attribute .

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

In JSF Html Tag Library there are 25 core tags .


All JSF Html Tags :
• column creates column in a dataTable
• commandButton creates button
• commandLink creates link that acts like a pushbutton
• dataTable creates a table control
• form creates a form
• graphicImage displays an image
• inputHidden creates hidden field
• inputSecret creates input control for password
• inputText creates text input control (single line)
• inputTextarea creates text input control (multiline)
• message displays the most recent message for a component
• messages displays all messages
• outputFormat creates outputText, but formats compound messages
• outputLabel creates label
• outputLink creates anchor
• outputText creates single line text output
• panelGrid creates html table with specified number of columns
• panelGroup used to group other components where the specification
requires one child element
• selectBooleanCheckbox creates checkbox
• selectManyCheckbox creates set of checkboxes
• selectManyListbox creates multiselect listbox
• selectManyMenu creates multiselect menu
• selectOneListbox creates single select listbox
• selectOneMenu creates single select menu
• selectOneRadio creates set of radio buttons
• JSF Core Tags:

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:

f: view tag is used to create top level view


f: subview tag is used to create subview of a view.
f: validator tag is used to add a validator to a component.
f: converter tag is used to add an arbitrary converter to a component.
f: actionListener tag is used to add an action listener to a component.
f:valueChangeListener tag is used to add a valuechange listener to a component

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.
In JSF Core Tag Library there are 18 core tags .

All JSF Core Tags:


• f :view Creates the top-level view
• f:subview Creates a subview of a view
• f:attribute Adds an attribute to a component
• f:param Constructs a parameter component
• f:converter Adds an arbitrary converter to a component
• f:converterDateTime Adds a datetime converter to a component
• f:converterNumber Adds a number converter to a component
• f:actionListener Adds an action listener to a component
• f:valueChangeListener Adds a valuechange listener to a component
• f:validator dds a validator to a component
• f:validateDoubleRange Validates a double range for a component’s value
• f:validateLength Validates the length of a component’s value
• f:validateLongRange Validates a long range for a component’s value
• f:facet Adds a facet to a component
• f:loadBundle Loads a resource bundle, stores properties as a Map
• f:selectitems Specifies items for a select one or select many component
• f:selectitem Specifies an item for a select one or select many component
• f:verbatim Adds markup to a JSF page
• In this we will understand the life cycle of JSF application.
• Life cycle of a JSF web application starts when user makes a request. On submission of
a page various further tasks are performed like validation of data provided in
components in the view, data conversion according to types specified on server side etc.
So series of steps that an application follows is called life cycle.

• A JSF application typically follows six steps in its life :


• 1. Restore view phase :

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.
• 2. Apply request values phase :

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.
• 3. Process validations phase :

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.
• 4. 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.
• 5. Invoke application phase :

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.
• 6. Render response phase:
In this phase JSP container renders the page back to the user,if jsp is used by application
i.e. view is displayed with all of its components in their current state.If this is an initial
request, the components will be added to the component tree. If this is not an initial
request, the components are not added because they are already added to the tree.The
state of the response is saved after rendering of the content of the view, so that
subsequent requests can access it and it is available to the restore view phase.

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:
Model : handles data and logic.
View : handles output (presentation)

Controller: handles processing of an application.

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.

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:
<input type=”text” name=”ID” value=”current_value”/>
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 :
1-encodeBegin() in doStartTag() and
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.

Sometimes we may wish to customize the renderers of an existing RenderKit and sometimes
create our own RenderKit. We typically create renderers for our custom components.In this
case we have to register renderers with existing RenderKits in JSF configuration file faces-
config.xml.This renderer should define renderer-type of the original component. Also, you
should provide the renderer-class that points to your custom renderer. The renderer class
should extend javax.faces.render.Renderer class.

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

Standard render kits:


JSF defines a standard RenderKit and set of associated Renderers that generate html markup.
Renderer will be determined and handled automatically according to the tag used.
Developing JSF Application
In this section, we are going to display data from database in JSF based web applications.
The dataTable tag is used to create table on the page. The component is rendered as an html
<table> element. UIColumn child components are responsible for rendering columns of the
table. In these columns you can put any type of component like input text box, output text,
command button etc.<h:column> tag is used to create column. There can be many column
tags within dataTable tag. You can set header and footer in this table. For this <f:facet> tag is
used. data table component and its children column component can use header and footer
facet.
This section provides you the code to which uses this tag and some of its attributes. It uses
backing bean that supplies data to the data table to be rendered to the cells of the columns of
the table.
Code Description :
1.Create a web page "data.jsp" for display data.
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<f:view><html>
<head>

</head>
<body>
<center>
<br><br><br>
<h:dataTable id="dt1" value="#{tableBean.perInfoAll}" var="item" bgcolor="#F1F1F1" border="10"
cellpadding="5" cellspacing="3" rows="4" width="50%" dir="LTR" frame="hsides" rules="all" summary="This
is a JSF code to create dataTable." >

<f:facet name="header">
<h:outputText value="This is 'dataTable' demo" />
</f:facet>

<h:column>
<f:facet name="header">
<h:outputText value="First Name" />
</f:facet>
<h:outputText style="" value="#{item.firstName}" ></h:outputText>
</h:column>

<h:column>
<f:facet name="header">
<h:outputText value="Last Name"/>
</f:facet>
<h:outputText value="#{item.lastName}"></h:outputText>
</h:column>

<h:column>
<f:facet name="header">
<h:outputText value="Username"/>
</f:facet>
<h:outputText value="#{item.uname}"></h:outputText>
</h:column>

<f:facet name="footer">
<h:outputText value="The End" />
</f:facet>

</h:dataTable><br>

</center>
</body></html></f:view>

2. Create a Bean class "TableBean.java".


package roseindia;
import java.sql.*;
import java.util.*;

public class TableBean {

Connection con ;
Statement ps;
ResultSet rs;
private List perInfoAll = new ArrayList();

public List getperInfoAll() {


int i = 0;
try
{

Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql:/
/localhost:3306/userdetails","root","root");
ps = con.createStatement();
rs = ps.executeQuery("select * from user");
while(rs.next()){
System.out.println(rs.getString(1));
perInfoAll.add(i,new perInfo(rs.getString(1),
rs.getString(2),rs.getString(3)));
i++;

}
catch (Exception e)
{
System.out.println("Error Data : " + e.getMes
sage());
}
return perInfoAll;
}

public class perInfo {

String uname;
String firstName;
String lastName;

public perInfo(String firstName,String lastName,Str


ing uname) {
this.uname = uname;
this.firstName = firstName;
this.lastName = lastName;

public String getUname() {


return uname;
}

public String getFirstName() {


return firstName;
}

public String getLastName() {


return lastName;
}

}
3. Mapping for Bean class "faces-config.xml".
<?xml version="1.0"?>
<faces-config>
<managed-bean>
<managed-bean-
name>tableBean</managed-bean-name>
<managed-bean-
class>roseindia.TableBean</managed-
bean-class>
<managed-bean-scope>request</managed-
bean-scope>
</managed-bean>

</faces-config>
4.web.xml
<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>

<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>

<context-param>
<param-name>javax.faces.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config.xml</param-value>
</context-param>

<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>

<!-- Faces Servlet -->

<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup> 1 </load-on-startup>
</servlet>
<!-- Faces Servlet Mapping -->
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>

</web-app>
Output :
Database Table : "user"

In this section, you will learn more about html tags provided in JSF. JSF HTML tags are used
for design the page by using server side code. This tag is used by specifying the uri and prefix
attribute of the taglib directive at the top of your JSP file. These are illusrated below as
follows:
http://java.sun.com/jsf/html
This is the uri for the JSF html tags. And for the prefix value commonly "h" is used but you
can put anything as value of the prefix attribute of the taglib directive. When you declare any
html tag as a JSF tag then you should write the tag as follows:
<htmlprefixvalue:tagName attribute1="value"
attribute2="value"></htmlprefixvalue:tagName attribute1="value"
attribute2="value">.
This is the syntax of specifying the html tag as a jsf tag. You can take an example of creation
an input box by using jsf html tag as follows:
If the prefix value is "h" then the syntax will be seen like : <h:inputText value="This is a
text box."></h:inputText>.
All the html tags have been used in the Rose India JSF Tutorial as you will get one by one
ahead. You can skip for next section for getting html tags overview with complete code
examples that can be used directly in your web application for creating several html
components as the need of your application.
Code Description:
<%@ page contentType="text/html" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<f:view>
<html>
<head><title>jsf h:column example</title></head>

<body>
<h:dataTable border="1">
<f:facet name="header">
<h:outputText value="This is header."/>
</f:facet>
<h:column>
<f:facet name="header">
<h:outputText value="Student"/>
</f:facet>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Marks" />
</f:facet>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Percent" />
</f:facet>
</h:column>
<f:facet name="footer">
<h:outputText value="This is footer."/>
</f:facet>
</h:dataTable>
</body>
</html>
</f:view>

HTML Source Code:


<html>
<head><title>jsf h:column example</title></head>

<body>
<table border="1">
<thead>
<tr><th colspan="3" scope="colgroup">This is header.</th></tr>
<tr>
<th scope="col">Student</th>
<th scope="col">Marks</th>
<th scope="col">Percent</th>
</tr>
</thead>
<tfoot>
<tr><td colspan="3">This is footer.</td></tr>
</tfoot>
<tbody>
</tbody>
</table>
</body>
</html>

JSF column tag has some attribute for different purposes. These attributes are explained
below:
• rendered: This is an attribute of the column tag that is optional. This attribute can hold
String typed value. This attribute value indicates that the component should be rendered
during the rendering period.
• binding: This attribute is also optional and take a String typed value. Specified value is
linked with the backing bean through the attribute of the tag.
• id: This attribute of the column tag is specified only for identification of the specific tag.
This section illustrates more about commandButton tag in JSF. This tag renders an HTML
submit button. This button can be associated with bean. You can perform any operations at
particular event by associating actionListener class for event handling. You can do any thing
with JSF component by the external resources like showing message from the message bundle
and handling form data after submission the form by backing bean.
This section also providing a program with complete code which display a command button
inside a form. When you will click on the button, it's action attributes send a value "page1" to
the faces-config.xml file where navigation has been made with the "page1" value. And the
navigation refers the control to the Index page.
Code Description:
<%@ page contentType="text/html" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<f:view>
<html>
<head><title>jsf h:commandButton example</title></head>

<body>
<h:form>
<h:commandButton value="Go To Index Page." action="page1" />
</h:form>
</body>
</html>
</f:view>

Rendered Output:
HTML Source Code:
<html>
<head><title>jsf h:commandButton example</title></head>

<body>
<form id="_id0" method="post" action="/
h-tags/pages/commandButton/commandButton.jsf" enctype="application
/x-www-form-urlencoded">
<input type="submit" name="_id0:_id1" value="Go
To Index Page." />
<input type="hidden" name="_id0" value="_id0" />
</form>
</body>
</html>

JSF commandButton tag has some attribute for different purposes. These attributes are
explained below:
• action: This attribute holds a value for passing values from the page to the faces-
config.xml file where the operation or navigation from the page to another page is
decided.
• actionListener: The actionListener attribute of the commandButton tag is used to assign
an action listener method from backing bean that performs the specific operation.
• id: Value of the attribute is used for identifying the component uniquely. This attribute
must have a unique value in the closest container.
• immediate:It's value is a boolean value that indicates for the component events that
should be sent to registered event listeners immediately. The immediate attribute allows
you to turn off validation for a particular component.
• rendered: This attribute takes a boolean value that indicates for the rendering it or not in
the view.
• value: This is the attribute holding the default value for the component whether it is
specified directly or by the backing bean or any other external resources like message
bundle.
• accesskey: This is the html attribute which specify key by pressing that key the
component will be focused and accessed.
• alt: This is also a html attribute that is used for showing the textual description on mouse
over of the component.
• dir: This attribute sets the value which define the component text direction. It sets the
value like "LTR" means "left-to-right" and "RTL" means "right to left" direction.
• disabled: This attribute takes a boolean value. If the value is true then the component
will be disabled otherwise the component will be enable.
• image: This attribute takes a relative or absolute url of the image that has to be displayed
on the component. The image attribute is used for showing image on the component.
• lang: It sets the code for the language to be used in the markup generated by this
component.
• onblur: This attribute indicates the event of the component. As the value of this attribute
is defined as a JavaScript method which has to be performed when the component loses
the focus.
• onchange: Specified JavaScript method is executed when the value has changed on
losing focus after gaining focus.
• onclick: In the attribute, a JavaScript method is specified that is called when the
component is clicked by user.
• ondblclick: This attribute indicates for performing the specified operation when the
component is clicked two times continuously (or double click).
• onfocus: The JavaScript method can be called for the component when the component is
focused.
• onkeydown: The specified JavaScript method or operation is performed when the key is
pressed down over the component.
• onkeypress: This is the event of the component. It indicates the key press event. You can
call a JavaScript method on the event of the component whatever you have mentioned.
• onkeyup: The specified JavaScript method is executed when key is released over this
component.
• onmousedown: Specified JavaScript method is executed when mouse is pressed down
over the component or element.
• onmousemove: This attribute sets the JavaScript code to executed when the mouse
pointer is moved within the component or element.
• onmouseout: This attribute sets the JavaScript code to execute when the mouse pointer is
moved away from the element or the component.
• onmouseover: This attribute sets the JavaScript code to execute when the mouse pointer
is moved inside the element or the component.
• onmouseup: This attribute sets the JavaScript code to executed when the mouse pointer
is released from the component.
• onselect: When you select the text contained by the component or element then the value
of the attribute (JavaScript code) will be executed.
• readonly: This attribute sets the boolean value for making the component read-only or
not.
• style: If you want ot add any CSS with the component then you can put the style as the
value of the attribute. Added CSS will be applied on for the component.
• styleClass: This attribute holds the CSS class name which is defined in the external style
sheet.
• tabindex: This attribute sets the tab index for the component. When you press the TAB
key then the component will be focused after focusing all those components whose tab
index is less than the component.
• title: This attribute holds a string value that is shown as a tool-tip text of a component or
element.
• type: This attribute tells the component type whether it is submit type or reset etc.
• binding: This attribute binds the specified value with the backing bean.
This section illustrates you about the JSF commandLink tag which is rendered as a anchor tag.
And this tag behaves as a command button for the form submission and this tag is also used
for the event handling purposes through the backing bean. This tag has text that can be labeled
by some external resources like properties file from the message bundle.
Here, you will see more about the commandLink tag of JSF how is it used in JSF
programming. There is a program with the complete code of JSF has been given for
understanding the procedure of using the tag.
Code Description:
<%@ page contentType="text/html" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<f:view>
<html>
<head><title>jsf h:commandLink example</title></head>

<body>
<h:form>
<h:commandLink value="Go for list of examples."
action="page2" />
</h:form>
</body>
</html>
</f:view>

Here, when your run the above program, output will be seen like the following image in which
the text "Go for list of examples." is looking like a hypertext. This is not only a anchor tag.
This link behaves like a command button. You can perform an action at the specific event.
Rendered Output:
When you run the above example, your JSF tags are converted in to HTML code that is given.
Following html source code is for the above written JSF code.
HTML Source Code:
<html>
<head><title>jsf h:commandLink
example</title></head>

<body>
<form id="_id0" method="post"
action="/h-tags/pages/commandLink/
commandLink.jsf" enctype="application/x-www-
form-urlencoded">
<a href="#"
onclick="document.forms['_id0']
['_id0:_idcl']
.value='_id0:_id1';
document.forms['_id0'].submit(); return
false;">Go
for list of examples.</a>
<input type="hidden"
name="_id0" value="_id0" /><input
type="hidden" name="_id0:_idcl" />
</form>
</body>
</html>

This JSF tag has some attributes these explained as follows:


• accesskey: This attribute set the key for the component through which the component
can be accessed. Specified key is also used for transferring focus from one component to
the component where it mentioned in with the JSF commandLink tag.
• action: This is also an attribute of the JSF commandLink tag. This attribute is used for
handling events from the backing bean or any other resources to invoke the component
when the component is activated by user. This type of action event is completed through
a action method of the backing bean class. This method will either return a boolean value
true or false by whom the Java Server Faces MVC Framework is designed. And
navigations are depended on generated events and actions.
• actionListener: This attribute sets a method-binding expression with a backing bean.
This method handles events.
• binding: This attribute binds values with backing bean.
• charset: This attribute sets the character encoding for the document that linked to by the
hyperlink.
• coords: When you are using the link with a client-side image map, this attribute sets the
position and the shape of spot on the screen.
• dir: This attribute set the direction of the text. The value for the attribute is accepted as
"LTR" (left to right) or "RTL" (right to left).
• hreflang: This attribute sets the language code for the resource linked to by the
hyperlink.
• id: This attribute sets the name for the identification of the component. It's value will be
unique in the closest naming container.
• immediate: It's value is a boolean value that indicates for the component events that
should be sent to registered event listeners immediately. The immediate attribute allows
you to turn off validation for a particular component.
• lang: It sets the code for the language to be used in the markup generated by this
component.
• onblur: This attribute sets JavaScript code when the component loses the focus.
• ondblclick: This attribute sets the JavaScript code when the component has been double-
clicked over the component.
• onfocus: This attribute sets the JavaScript code when the component receives focus.
• onkeydown: This attribute sets the JavaScript code when key is pressed down over the
element.
• onkeypress: This attribute sets the JavaScript code when key is pressed and released
over the element or the component.
• onkeyup: This attribute sets the JavaScript code when key is released over the element or
component.
• onmousedown: Specified JavaScript method is executed when mouse is pressed down
over the component.
• onmousemove: This attribute sets the JavaScript code to executed when the mouse
pointer is moved within the component.
• onmouseout: This attribute sets the JavaScript code to execute when the mouse pointer is
moved away from the element.
• onmouseover: This attribute sets the JavaScript code to execute when the mouse pointer
is moved inside the element.
• onmouseup: This attribute sets the JavaScript code to executed when the mouse pointer
is released from the component.
• rel: This attribute tells you about the relationship between the current document and the
document linked to by the hyperlink. It's values are the list of the link types separated by
space from each other.
• rev: This attribute identifies a reserve link from the document linked to by the hyperlink
to the current document. It's values are a list of link types separated by space from each
other.
• rendered: This attribute takes a boolean value that indicates for the rendering it or not in
the view.
• shape: This attribute sets the shape of the hotspot for viewing on the screen during the
client side image mapping. It's some valid value is "rect" for the rectangular region,
"default" for the entire region, "circle" for the circular region and "poly" for the
polygonal region.
• style: If you want ot add any CSS with the component then you can put the style as the
value of the attribute. Added CSS will be applied on for the component.
• styleClass: This attribute holds the CSS class name which is defined in the external style
sheet.
• tabindex: This attribute sets the tab index for the component. When you press the TAB
key then the component will be focused after focusing all those components whose tab
index is less than the component.
• target: This attribute set the identification of a frame in which the resource has to be
displayed that is linked to by the hyperlink.
• title: This attribute holds a string value that is shown as a tool-tip text of a component or
element.
• type: This attribute tells the component type whether it is submit type or reset etc.
• value: This attribute set the display value for the component. It will be directly or any
other resources like the backing bean or a message bundle. You can manage the backing
bean for the value of the component or element.

JSF dataTable Tag

This tag is used to create table on the page. The component is rendered as an html <table>
element. UIColumn child components are responsible for rendering columns of the table. In
these columns you can put any type of component like input text box, output text, command
button etc.<h:column> tag is used to create column. There can be many column tags within
dataTable tag. You can set header and footer in this table. For this <f:facet> tag is used. data
table component and its children column component can use header and footer facet.
We can associate this table element to backing bean. So we can obtain data from this backing
bean and display it on the table. Association of backing bean can also be helpful for event
handling purpose. Suppose we inserted command button in columns of the table then event
handling can be applied here. If you want to customize the table then cascading stylesheet
(CSS) can be used. This will help you to enhance the appearance of the table's headers, footer,
rows, columns.
This section provides you the code to which uses this tag and some of its attributes. It uses
backing bean that supplies data to the data table to be rendered to the cells of the columns of
the table.
code description :
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<f:view><html><body>
<h:form>
<br><br><br>
<h:dataTable id="dt1" value="#{TableBean.perInfoAll}" var="item"
bgcolor="#F1F1F1" border="10" cellpadding="5" cellspacing="3"
first="0" rows="4" width="50%" dir="LTR" frame="hsides"
rules="all" summary="This is a JSF code to create dataTable." >

<f:facet name="header">
<h:outputText value="This is 'dataTable' demo" />
</f:facet>

<h:column>
<f:facet name="header">
<h:outputText value="id" />
</f:facet>
<h:outputText value="#{item.id}"></h:outputText>
</h:column>

<h:column>
<f:facet name="header">
<h:outputText value="name"/>
</f:facet>
<h:outputText value="#{item.name}"></h:outputText>
</h:column>

<h:column>
<f:facet name="header">
<h:outputText value="phone"/>
</f:facet>
<h:outputText value="#{item.phone}"></h:outputText>
</h:column>

<h:column>
<f:facet name="header">
<h:outputText value="city"/>
</f:facet>
<h:outputText value="#{item.city}"></h:outputText>
</h:column>

<h:column>
<f:facet name="header">
<h:outputText value="pin"/>
</f:facet>
<h:outputText value="#{item.pin}"></h:outputText>
</h:column>

<f:facet name="footer">
<h:outputText value="The End" />
</f:facet>
</h:dataTable><br><br>

</h:form>
</body></html></f:view>

Rendered Output :

In this example we have used <h:dataTable> tag. This <h:dataTable> tag has many attributes
to give form and shape to the table and getting data from backing bean's attribute to display
this data to the columns of the table. <f:facet> tag is used to create a header and a
footer for a dataTable component and it can create the same for columns also. So in this
example we have used facet tag in dataTabe tag to create header and footer of the table
component and in column tag also to create header for column. In this example, "This is
'dataTable' demo" is the header and "The End" is the footer for the table and "id" "name"
"phone" "city" "pin" are headers for columns. In his example we have populated data to the
table from bean named "TableBean". It contains an attribute "perInfoAll" that is an array of
objects of type "perInfo" class which contains some attributes like id, name, phone, city, pin
that is to be displayed on the table. In the value attribute of dataTable tag, we have specified
the binding expression to bind this component to the bean
(value="#{TableBean.perInfoAll}") and value specified in var attribute is used to populate
data to the column of the table from attributes defined in class perInfo
(value="#{item.id}"). The code for the bean has been given below (remember to specify it
in faces-cocfig.xml file) :
public class TableBean {

private perInfo[] perInfoAll = new perInfo[]{


new perInfo(101, "CHANDAN", "9891444444", "aaa", 11111),
new perInfo(102, "RAVI", "9911666666", "bbb" ,22222),
new perInfo(103, "JOHN", "9313888888", "ccc", 33333),
new perInfo(104, "ANDREW", "9911222222", "ddd" , 44444),
new perInfo(105, "SYMONDS", "9313999999", "eee", 55555),
};

public perInfo[] getperInfoAll() {


return perInfoAll;
}

public class perInfo {


int id;
String name;
String phone;
String city;
int pin;

public perInfo(int id, String name, String phone, String city,


int pin) {
this.id = id;
this.name = name;
this.phone = phone;
this.city = city;
this.pin= pin;
}

public int getid() {


return id;
}

public String getname() {


return name;
}

public String getphone() {


return phone;
}

public String getcity() {


return city;
}
public int getpin() {
return pin;
}

HTML Source Code:


<html>
<body>
<form id="_id0"
method="post"
action="/dt/data.jsf;jsessionid
=B95AF7B5F7D80BCB5638B91AC8154C33"
enctype="application/x-www-form-
urlencoded">
<br><br><br>
<table id="_id0:dt1"
bgcolor="#F1F1F1" border="10"
cellpadding="5" cellspacing="3"
dir="LTR" frame="hsides" rules="all"
summary="This is a JSF code to create
dataTable." width="50%">
<thead>
<tr><th
colspan="5" scope="colgroup">This is
'dataTable' demo</th></tr>
<tr>
<th
scope="col">id</th>
<th
scope="col">name</th>
<th
scope="col">phone</th>
<th
scope="col">city</th>
<th
scope="col">pin</th>
</tr>
</thead>
<tfoot>
<tr><td
colspan="5">The End</td></tr>
</tfoot>
<tbody>
<tr>
<td>101</td
>
<td>CHANDAN
</td>
<td>9891444
444</td>
<td>aaa</td
>
<td>11111</
td>
</tr>
<tr>
<td>102</td
>
<td>RAVI</t
d>
<td>9911666
666</td>
<td>bbb</td
>
<td>22222</
td>
</tr>
<tr>
<td>103</td
>
<td>JOHN</t
d>
<td>9313888
888</td>
<td>ccc</td
>
<td>33333</
td>
</tr>
<tr>
<td>104</td
>
<td>ANDREW<
/td>
<td>9911222
222</td>
<td>ddd</td
>
<td>44444</
td>
</tr>
</tbody>
</table>
<br><br>
<input type="hidden"
name="_id0" value="_id0" />
</form>
</body>
</html>

This tag has some attributes. These are listed below :


• id : This is used to uniquely identify the table component. This must be unique within
the closest parent component.
• value : It represents the value of the component. It represents the value over which
iteration is to be done. It may be an array or any iterator object .
• var : This is the name of the variable created by the data table that represents the current
item in the value. This attribute helps exposing the data in the rows of the table.
• bgcolor : This attribute is used to set the background color for the table.
• border : We can set the width of the table's border around the table.
• cellpadding : This sets the space between the content and the border of the cell.
• cellspacing : It specifies the amount of space to leave between cells.
• first : This is used to specify the row number of the first row from which displaying is to
be started onwards. Suppose, this property is set to 3,displaying will be started from the
third row of the underlying data.
• rows : This attribute specifies the number of rows to display. This displaying will be
started from the index specified in the "first" attribute. If we set this attribute to zero then
all rows will be displayed.
• width : This is used to set the width of the entire table. Its value is specified in %.
Suppose we set it to 50% then this table will be shown in the 50% space of the width of
your screen.
• dir : This attribute indicates the direction of the text to be displayed in the cell. It takes
"LTR" (left-to-right) and "RTL" (right-to-left) values. If we don't specify this attribute
then the content will be displayed in center.
• frame : This attribute specifyes which sides of the frame surrounding this table will be
visible. This attribute can take some values shown below :
1. none No side, Default Value
2. above Top side only
3. below Bottom side only
4. hsides Top and bottom sides only
5. vsides Right and left sides only
6. lhs Left hand side only
7. rhs Right hand side only
8. box All four sides
9. border All four sides
• rules : This attribute is used to draw lines between cells. It can take some values given
below :
1. none No rules, default value
2. groups Between row groups
3. rows Between rows only
4. cols Between columns only
5. all Between all rows and columns
• summary : You can specify summary of the purpose of the table.
• rendered : It takes boolean value.This indicates whether or not this component should be
rendered. Its default value is "true". If it is set to false then it prevents rendering of this
component to the page.
• captionClass : Space separated list of CSS class or classes that will be applied to any
caption generated for this table.
• captionStyle : It specifies CSS style or styles to be applied when this caption is rendered.
• columnClasses : Comma seperated list of CSS classes that will be applied to the columns
of this table.
• footerClass : This attribute takes Space-separated list of CSS style class or classes that
will be applied to aheaderter generated for this table.
• headerClass : This attribute takes Space-separated list of CSS style class or classes that
will be
applied to any header generated for this table.
• rowClasses : It is a list of CSS classes applied to the rows of the table.These classes
should be separated by comma. If we want to apply CSS class for individual rows then
we can specify space separated list of CSS classes. Style classes are applied to rows in
the same order that they are
defined. If we have two CSS classes then first class is applied to the first row and the
second one is applied to the second. Then again in the third row, the first CSS is applied
and so on. This process goes on till the last row of the table.
• lang : It sets the base language of an element’s attributes and text i.e. the language used
in the generated markup for this component.
• styleClass : It sets the name of CSS classor classes that is applied at the time of rendering
the element.
• title : The title attribute is used to set the tooltip text to display for the rendered
component.Tooltip describes an element when rendered to the client.
• binding : It is a value binding expression that is used to link component to a property in a
backing bean.
• onclick : It sets the JavaScript code to execute when a pointer button is clicked over this
element.
• ondblclick : It sets the JavaScript code to execute when a pointer button is double
clicked over this element.
• onkeydown : It sets the JavaScript code to execute when a key is pressed down over this
element.
• onkeypress : It sets the JavaScript code to execute when a key is pressed and released
over this element.
• onkeyup : It sets the JavaScript code to execute when a key is released over this element.
• onmousedown : It sets the JavaScript code to execute when a pointer button is pressed
down over this element.
• onmousemove : It sets the JavaScript code to execute when a pointer button is moved
within this element.
• onmouseout : It sets the JavaScript code to execute when a pointer button is moved away
from this element.
• onmouseover : It sets the JavaScript code to execute when a pointer button is moved
onto this element.
• onmouseup : It sets the JavaScript code to execute when a pointer button is released over
this element.
This tag renders html form element which contains the data that is submitted with the form.
This tag uses "POST" method. The components under the particular form i.e. children of the
form only are processed. "id" attribute is used to uniquely identify the form. CSS can be used
to make it more attractive.
Code Description :
<%@ page contentType="text/html" %>
<%@ taglib
uri="http://java.sun.com/jsf/html"
prefix="h" %>
<%@ taglib
uri="http://java.sun.com/jsf/core"
prefix="f" %>

<f:view>
<html>
<head><title>jsf h:form
example</title></head>
<body>
<h:form>
<h:outputText value="Enter your
name: " /></td>
<h:inputText
value="#{StoreNameBean.personName}" /
>
<h:commandButton action="result"
value="Say Hello" />
</h:form>
</body>
</html>
</f:view>
Rendered Output :
Html Source Code :
<html>
<head><title>jsf h:form
example</title></head>
<body>
<form id="_id0" method="post"
action="/h-tags/pages/form/form.jsf"
enctype="application/x-www-form-
urlencoded">
Enter your name: </td>
<input type="text"
name="_id0:_id2" />
<input type="submit"
name="_id0:_id3" value="Say Hello" />
<input type="hidden" name="_id0"
value="_id0" /></form>
</body>
</html>
This tag contains some attributes that are discussed below :
• id : This attribute is used to uniquely identify the element within the closest container.
• rendered : Its a boolean attribute. Its default value is true. It determines whether this
component should be rendered or not.
• binding : It takes the value binding expression that is used to link the component to the
property of the backing bean.
• dir : It is used to set the direction of the text to be displayed. It can take two values
LTR(left to right) and RTL (right to left).
• lang : It is used to set the base language of the component when displayed.
• style : It is used to set the CSS style definition for the component.
• title : It is the standard html attribute. It is used to set the tooltip text for this component.
• styleClass : It is used to set the CSS class for the component.
• target : This is used to identify the name of the frame where the response generated by
the server is displayed when we submit the form.
• accept : Its a comma separated list of content types that is handled by the server which
processes this form.
• acceptcharset : It is used to list character encoding used for the data input by the user
and that will be accepted by the user.
• enctype : This is used to set the content type of the data that will be submitted to the
server.
• onclick : Script to be invoked when the element is clicked.
• ondblclick : It is used for Java Script code to be invoked when the element is double-
clicked.
• onmousedown : It is used for Java Script code to be invoked when the pointing device is
pressed over this element.
• onmouseup : It is used for Java Script code to be invoked when the pointing device is
released over this element.
• onmouseover : It is used for Java Script code to be invoked when the pointing device is
moved into this element.
• onmousemove : It is used for Java Script code to be invoked when the pointing device is
moved while it is in this element.
• onmouseout : It is used for Java Script code to be invoked when the pointing device is
moves out of this element.
• onkeypress : It is used for Java Script code to be invoked when a key is pressed over this
element.
• onkeydown : It is used for Java Script code to be invoked when a key is pressed down
over this element.
• onkeyup : It is used for Java Script code to be invoked when a key is released over this
element.
• onreset : It is used for Java Script code to be invoked when form is reset.
• onsubmit : It is used for Java Script code to be invoked when form is submitted.

JSF graphicImage Tag


This section explains about "graphicImage" tag. This displays the image on the page. This
tag renders an html "img" element. This tag renders the image file stored in the location
specified in the "value" attribute of "graphicImage" tag. If this image file is not present in
the specified location then the value of the alt attribute is displayed instead of the desired
image file. In this example, value attribute is set to the location "/image/rose.gif" in the web-
application root directory and alt attribute is set to "The image could not be found.". So this
image is displayed on the page, if there is any problem in getting this image file
("/image/rose.gif") then the text specified in the alt attribute ("The image could not be
found.") is displayed on the page. We can set width, height of the image. If we want tooltip
for this image to be displayed when focus comes to the image, then we can use title attribute.
There are several attributes of this tag to give it different look and structure.
This section provides you the code that uses this tag and some of its attributes to render the
image on the page.

Code Description :

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


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

<f:view>
<html>
<body>
<h:form><br>
<h:graphicImage id="gi" alt="The image
could not be found." value="/image/rose.gif" width="250"
height="250" title="This is demo for 'graphicImage' tag"
></h:graphicImage>
</h:form>
</body>
</html>
</f:view>

Rendered Output :
Html Source Code :
<html>
<body>
<form id="_id0" method="post"
action="/graphicImage/graphicImage.jsf" enctype="application/x-
www-form-urlencoded"><br>
<img id="_id0:gi" src="/graphicImage/image/rose.gif"
alt="The image could not be found." height="250" title="This is
demo for 'graphicImage' tag" width="250" />
<input type="hidden" name="_id0" value="_id0" />
</form>
</body>
</html>

All attributes of graphicImage tag have been described below:


• id : This is the identifier for the component. This must be the unique value within the
closest parent component.
• alt : This is standard html attribute. This is the alternate textual value to be displayed in
the absence of the image file specified in the value attribute.
• value : This attribute takes context relative URL to the image. URL is called relative to
the context path of the web-application if URL starts with '/'. This image is rendered, if
present, on the page.
• url : Its an alias for the value attribute.
• width : It is used to set new width of the image over the natural width.
• height :It is used to set new height of the image over the natural height.
• title : This is standard html attribute. It sets the tooltip for the component.
• rendered : It takes boolean value. Its default value is "true". It indicates whether the
component should be rendered or not.
• dir : It sets the direction of the text to be displayed. It can take two values "LTR" (Left to
Right) and "RTL" (Right to Left).
• lang : This is a standard html attribute. It is used to describe the base language used in
the markup generated for this component.
• ismap : This takes a boolean value. This is used to indicate whether this image is to be
used as a server side image or not.
• onclick : It sets the Java Script code to be invoked when the element is clicked.
• ondblclick : It sets the Java Script code to be invoked when the element is double-
clicked.
• onkeydown : It sets the Java Script code to be invoked when a key is pressed down over
this element.
• onkeypress : It sets the Java Script code to be invoked when a key is pressed over this
element.
• onkeyup : It sets the Java Script code to be invoked when a key is released over this
element.
• onmousedown : It sets the Java Script code to be invoked when the pointing device is
pressed over this element.
• onmousemove : It sets the Java Script code to be invoked when the pointing device is
moved within this element.
• onmouseout : It sets the Java Script code to be invoked when the pointing device is
moves out of this element.
• onmouseover : It sets the Java Script code to be invoked when the pointing device is
moved into this element.
• onmouseup : It sets the Java Script code to be invoked when the pointing device is
released over this element.
• style : This is used to set the CSS style definition which will be applied to the component
when it is rendered.
• styleClass : This is used to set the CSS class which will be applied to the component
when it is rendered.
• usemap : This is html map element. This describes the name of client side image map for
which this element provides the image.
• binding : Its a value binding expression that is used to link the component to the backing
bean property.
JSF inputHidden Tag

This section describes the inputHidden JSF tag. This tag is used to create the field that is
invisible to the user. This is the field that is used to pass the variables from one page to
another. It renders the html input element with the type attribute set to "hidden".

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

<f:view>
<html>
<body>
<h:form><br>
<h:inputHidden id="ih" value="hv"></h:inputHidden>
</h:form>
</body>
</html>
</f:view>

Rendered Output :
There is no rendered output for this tag . This gives invisible element as an output.
Html Scorce Code :
<html>
<body>
<form id="_id0" method="post"
action="/inputHidden/inputHidden.jsf" enctype="application/x-www-form-
urlencoded"><br>
<input id="_id0:ih" type="hidden" name="_id0:ih" value="hv" />
<input type="hidden" name="_id0" value="_id0" />
</form>
</body>
</html>

There is a list of all attributes that can be used in this inputHidden tag:
• id : This is set to uniquely identify the component. So this must be the unique value
within the closest container.
• value : This is the current value of the component.
• binding : This is used to set the binding expression that is used to link the component to
the backing bean's property.
• rendered : This is the boolean attribute that is set to describe that this component should
be rendered or not at the time of render response phase.
• required : This is the boolean attribute. User is required to provide the value for the field
or not at the time of submission of the form is indicated by this attribute.
• validator : It takes a method binding expression that represents validator method. This
method is called to validate the value of the component.
• immediate : This is the boolean attribute. This is used to ensure that the events should be
sent to the associated listener immediately. It should not be sent after validation phase.
• converter : It is used to register the converter instance to the component.
• valueChangeListener : It takes the method binding expression that notifies the value
change listener method. It notifies this method when value is changed and new value is
set for this component.

JSF inputSecret Tag


This section illustrates you more about the JSF HTML inputSecret tag. This tag is used to
create a text box for having password that is secret. This text box shows only a symbol for
every enteries. You can't understand the value of the text box by seeing.
Here, you will see in the program code that the value of the inputSecret tag has been assigned
"chandan" but by seeing it's output as given below, any one can't understand. This type of text
box helps you to keep your data secret.
Code Description:
<%@ page contentType="text/html" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<f:view>
<html>
<head><title>jsf h:message example</title></head>

<body>
<h:inputSecret value="chandan" />
</body>
</html>
</f:view>

Rendered Output:
HTML Source Code:
Following is the html code generated by the browser when your JSF program is run.
<html>
<head><title>jsf h:message example</title></head>

<body>
<input type="password" name="_id0" value="" />
</body>
</html>

All attributes of the inputSecret tag are explained as follows:


• accesskey: This is standard html attribute. It is used to set the access key for the
element which is used to send the focus to the element when pressed.
• alt: This is used as an alternate text that is displayed when browser is not able to
display the element.
• binding: It takes the value binding expression that is used to link the component to the
property of the backing bean.
• converter: This specifies the converter for the component. This can be static value or
EL expression.
• dir: It is used to set the direction of the text to be displayed. It can take two values
LTR(left to right) and RTL (right to left).
• disabled: Its a boolean attribute. This is used to disable the element to receive focus,
when it is set to true.
• id: This attribute is used to uniquely identify the element within the closest container.
• immediate: Its a boolean attribute. It is used to identify during which phase value
change event should occur. If this attribute is set to true then in place of firing the event
during the process validation phase, these event are sent immadiately at the end of
apply request values phase.
• lang: It is used to set the base language of the component when displayed.
• maxlength: It is used to set the maximum length of character that can be input into the
text field.
• onblur: It is used to set the java script code to execute when focus is lost from the
element.
• onchange: It is used to set the java script code to execute when element is modified.
• onclick: Script to be invoked when the element is clicked.
• ondblclick: It is used for Java Script code to be invoked when the element is double-
clicked.
• onfocus: It is used to set the java script code to execute when element receives the
focus.
• onkeydown: It is used for Java Script code to be invoked when a key is pressed down
over this element.
• onkeypress: It is used for Java Script code to be invoked when a key is pressed over
this element.
• onkeyup: It is used for Java Script code to be invoked when a key is released over this
element.
• onmousedown: It is used for Java Script code to be invoked when the pointing device
is pressed over this element.
• onmousemove: It is used for Java Script code to be invoked when the pointing device
is moved while it is in this element.
• onmouseout: It is used for Java Script code to be invoked when the pointing device is
moves out of this element.
• onmouseover: It is used for Java Script code to be invoked when the pointing device
is moved into this element.
• onmouseup: It is used for Java Script code to be invoked when the pointing device is
released over this element.
• onselect: It is used to set the java script code to execute when text of the component is
selected by the user.
• readonly: Its a boolean attribute. It is used to indicate the user that its value can't be
modified, if it is set to true.
• redisplay: This is a boolean attribute. This is used to specify that the password, that
have been entered previously, has to be rendered again or not. Its default value is
"false" because we generally need not to do this for security reasons.
• rendered: Its a boolean attribute. Its default value is true. It determines whether this
component should be rendered or not.
• required: Its a boolean attribute. It indicates that its value is required by the user
before the submission of the form to the server. If it is set to true and value is not
provided then an error message comes.
• size: It is used to set the width (in character) of the component.
• style: It is used to set the CSS style definition for the component.
• styleClass: It is used to set the CSS class for the component.
• tabindex: This is a standard html attribute. It is used to set the order of receiving the
focus on the movement of TAB key by the user.
• title: It is the standard html attribute. It is used to set the tooltip text for this
component.
• validator: It takes the method binding expression. This expression represents the
validator method. This method is called at the time of validation of the component.
• value: This is to set the current value of the component.
• valueChangeListener: This also takes a method binding expression. This expression
represents value change listener method. This method will be called when new value is
set for this component.

JSF inputText tag

This tag is used to create html input element which has the type "text". It creates input text
field where text can be entered.
Code Description :

<%@ page contentType="text/html" %>


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

<f:view>
<html>
<head><title>jsf h:inputText example</title></head>
<body>
<h:inputText />
</body>
</html>
</f:view>
Rendered Output :

Html Source Code :


<html>
<head><title>jsf h:inputText
example</title></head>
<body>
<input type="text"
name="_id0" />
</body>
</html>
This tag contains some attributes that are discussed below :
• id : This attribute is used to uniquely identify the element within the closest container.
• rendered : Its a boolean attribute. Its default value is true. It determines whether this
component should be rendered or not.
• binding : It takes the value binding expression that is used to link the component to the
property of the backing bean.
• dir : It is used to set the direction of the text to be displayed. It can take two values
LTR(left to right) and RTL (right to left).
• lang : It is used to set the base language of the component when displayed.
• style : It is used to set the CSS style definition for the component.
• accesskey : This is standard html attribute. It is used to set the access key for the element
which is used to send the focus to the element when pressed.
• alt : This is used as an alternate text that is displayed when browser is not able to display
the element.
• converter : This specifies the converter for the component. This can be static value or EL
expression .
• disabled : Its a boolean attribute. This is used to disable the element to receive focus,
when it is set to true.
• immediate : Its a boolean attribute. It is used to identify during which phase value
change event should occur. If this attribute is set to true then in place of firing the event
during the process validation phase, these event are sent immadiately at the end of apply
request values phase.
• maxlength : It is used to set the maximum length of character that can be input into the
text field.
• onblur : It is used to set the java script code to execute when focus is lost from the
element.
• onchange : It is used to set the java script code to execute when element is modified.
• size : It is used to set the width (in character) of the component.
• title : It is the standard html attribute. It is used to set the tooltip text for this component.
• styleClass : It is used to set the CSS class for the component.
• onclick : Script to be invoked when the element is clicked.
• ondblclick : It is used for Java Script code to be invoked when the element is double-
clicked.
• onmousedown : It is used for Java Script code to be invoked when the pointing device is
pressed over this element.
• onmouseup : It is used for Java Script code to be invoked when the pointing device is
released over this element.
• onmouseover : It is used for Java Script code to be invoked when the pointing device is
moved into this element.
• onmousemove : It is used for Java Script code to be invoked when the pointing device is
moved while it is in this element.
• onmouseout : It is used for Java Script code to be invoked when the pointing device is
moves out of this element.
• onkeypress : It is used for Java Script code to be invoked when a key is pressed over this
element.
• onfocus : It is used to set the java script code to execute when element receives the
focus.
• onkeydown : It is used for Java Script code to be invoked when a key is pressed down
over this element.
• onkeyup : It is used for Java Script code to be invoked when a key is released over this
element.
• onselect : It is used to set the java script code to execute when text of the component is
selected by the user.
• readonly : Its a boolean attribute. It is used to indicate the user that its value can't be
modified, if it is set to true.
• required : Its a boolean attribute. It indicates that its value is required by the user before
the submission of the form to the server. If it is set to true and value is not provided then
an error message comes.
• tabindex : This is a standard html attribute. It is used to set the order of receiving the
focus on the movement of TAB key by the user.
• validator : It takes the method binding expression. This expression represents the
validator method. This method is called at the time of validation of the component.
• value : This is to set the current value of the component.
• valueChangeListener : This also takes a method binding expression. This expression
represents value change listener method. This method will be called when new value is
set for this component.
JSF inputTextarea tag

This tag is used to render html "textarea" element . It creates input text area where text can be
entered in multiple lines.
Code Description :
<%@ page contentType="text/html" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"
%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"
%>

<f:view>
<html>
<head><title>jsf h:outputLink example</title></head>
<body>
<h:inputTextarea
id="name"></h:inputTextarea><br/>
<h:outputLink value="../index.jsp">
<h:outputText value="Go to index page."/>
</h:outputLink>
</body>
</html>
</f:view>
Rendered Output :
Html Source Code :
<html>
<head><title>jsf h:outputLink
example</title></head>
<body>
<textarea id="name"
name="name"></textarea><br/>
<a href="../index.jsp">Go to index
page.</a>
</body>
</html>
This tag contains some attributes that are discussed below :
• id : This attribute is used to uniquely identify the element within the closest container.
• rendered : Its a boolean attribute. Its default value is true. It determines whether this
component should be rendered or not.
• binding : It takes the value binding expression that is used to link the component to the
property of the backing bean.
• dir : It is used to set the direction of the text to be displayed. It can take two values
LTR(left to right) and RTL (right to left).
• lang : It is used to set the base language of the component when displayed.
• style : It is used to set the CSS style definition for the component.
• accesskey : This is standard html attribute. It is used to set the access key for the element
which is used to send the focus to the element when pressed.
• cols : This is used to set the width (in characters) of the component.
• rows : This is used to set the height (in characters) of the component.
• converter : This specifies the converter for the component. This can be static value or EL
expression .
• disabled : Its a boolean attribute. This is used to disable the element to receive focus,
when it is set to true.
• immediate : Its a boolean attribute. It is used to identify during which phase value
change event should occur. If this attribute is set to true then in place of firing the event
during the process validation phase, these event are sent immadiately at the end of apply
request values phase.
• maxlength : It is used to set the maximum length of character that can be input into the
text field.
• onblur : It is used to set the java script code to execute when focus is lost from the
element.
• onchange : It is used to set the java script code to execute when element is modified.
• title : It is the standard html attribute. It is used to set the tooltip text for this component.
• styleClass : It is used to set the CSS class for the component.
• onclick : Script to be invoked when the element is clicked.
• ondblclick : It is used for Java Script code to be invoked when the element is double-
clicked.
• onmousedown : It is used for Java Script code to be invoked when the pointing device is
pressed over this element.
• onmouseup : It is used for Java Script code to be invoked when the pointing device is
released over this element.
• onmouseover : It is used for Java Script code to be invoked when the pointing device is
moved into this element.
• onmousemove : It is used for Java Script code to be invoked when the pointing device is
moved while it is in this element.
• onmouseout : It is used for Java Script code to be invoked when the pointing device is
moves out of this element.
• onkeypress : It is used for Java Script code to be invoked when a key is pressed over this
element.
• onfocus : It is used to set the java script code to execute when element receives the
focus.
• onkeydown : It is used for Java Script code to be invoked when a key is pressed down
over this element.
• onkeyup : It is used for Java Script code to be invoked when a key is released over this
element.
• onselect : It is used to set the java script code to execute when text of the component is
selected by the user.
• readonly : Its a boolean attribute. It is used to indicate the user that its value can't be
modified, if it is set to true.
• required : Its a boolean attribute. It indicates that its value is required by the user before
the submission of the form to the server. If it is set to true and value is not provided then
an error message comes.
• tabindex : This is a standard html attribute. It is used to set the order of receiving the
focus on the movement of TAB key by the user.
• validator : It takes the method binding expression. This expression represents the
validator method. This method is called at the time of validation of the component.
• value : This is to set the current value of the component.
• valueChangeListener : This also takes a method binding expression. This expression
represents value change listener method. This method will be called when new value is
set for this component.
JSF message Tag

In this section we will explain you JSF message tag. This is used to display the most recent
message for the component. This is used to show the message for a particular component. This
tag shows the message for the component specified in for attribute of message tag. If you
want to customize the message then CSS can be used. If you want to show the error message
for a component in a color and other information in different color then CSS can be helpful.

Code Description :
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<f:view>
<html>
<body>
<h:form>Enter text in this box :<br>
<h:inputText id="input_text" value="#{MessageBean.a}"
required="true"/>
<h:message for="input_text" /><br>
<h:commandButton action="Submit" value="Submit"/>
</h:form>
</body>
</html>
</f:view>

Rendered Output :
If this input text field is not filled by the user and submit is pressed then the error message is
flashed for this component to warn that this is the required field to be filled. It shows that it
can't be left blank because "required" field is set to "true" for the input field. The message
tag shows the error message related to this component because its "for" attribute is set to the
id for this input text field. So if this field is left blank before submitting the page, then the
output comes as below :

Html Source Code :


<html>
<body>
<form id="_id0" method="post"
action="/htmltag/pages/message.jsf"
enctype="application/x-www-form-urlencoded">
Enter text in this box :<br>
<input id="_id0:input_text" type="text"
name="_id0:input_text" value="" />
<br>
<input type="submit" name="_id0:_id2" value="Submit" />
<input type="hidden" name="_id0" value="_id0" /></form>
</body>
</html>

This tag has some attributes that can be used for different purpose. These attributes are
described below :
• id : It is the component identifier that must be unique in the closest container.
• binding : It takes the value binding expression that is used to link the component to the
property of the backing bean.
• rendered : Its a boolean attribute. It determines whether this component should be
rendered or not.
• for : This is the required attribute for the component. It takes the id for a component.
message tag displays the message for this component whose id has been specified in for
attribute.
• showSummary : Its a boolean flag. Its default value is true. It is used to determine
whether the summary part of the message should be included or not.
• showDetail :Its a boolean flag. Its default value is true. It is used to determine whether
the detail part of the message should be included or not.
• dir : It is used to set the direction of the text to be displayed. It can take two values
LTR(left to right) and RTL (right to left).
• lang : It is used to set the base language of the component when displayed.
• style : It is used to set the CSS style definition for the component.
• title : It is the standard html attribute.It is used to set the tooltip text for this component.
• styleClass : It is used to set the CSS class for the component.
• onclick : Script to be invoked when the element is clicked.
• ondblclick : It is used for Java Script code to be invoked when the element is double-
clicked.
• onmousedown : It is used for Java Script code to be invoked when the pointing device is
pressed over this element.
• onmouseup : It is used for Java Script code to be invoked when the pointing device is
released over this element.
• onmouseover : It is used for Java Script code to be invoked when the pointing device is
moved into this element.
• onmousemove : It is used for Java Script code to be invoked when the pointing device is
moved while it is in this element.
• onmouseout : It is used for Java Script code to be invoked when the pointing device is
moves out of this element.
• onkeypress : It is used for Java Script code to be invoked when a key is pressed over this
element.
• onkeydown : It is used for Java Script code to be invoked when a key is pressed down
over this element.
• onkeyup : It is used for Java Script code to be invoked when a key is released over this
element.
• infoClass : This is to determine the CSS class to be applied to information message.
• infoStyle : This is to determine the CSS style to be applied to information message.
• warnClass : This is to determine the CSS class to be applied for warning message.
• warnStyle : This is to determine the CSS style to be applied for warning message.
• errorClass : This is to determine the CSS class to be applied to error message.
• errorStyle : This is to determine the CSS style to be applied to error message.
• fatalClass : This is to determine the CSS class to be applied to fatal message.
• fatalStyle : This is to determine the CSS style to be applied to fatal message.
• tooltip : It is a boolean attribute. It is used to determine whether to show the summary
message in a tooltip or not.
JSF messages Tag

This tag is also like message tag which is also used to show all messages for the
components. If you want to customize the message then CSS can be used. If you want to show
the error message for a component in a color and other information in different color then CSS
can be helpful. Two layouts are supported for generated messages, table and list. If layout is
not specified then it takes list layout and all messages are displayed in a line.
Code Description :
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<f:view>
<html>
<body>
<h:form >Enter name and password below :<br>
<h:inputText id="name" required="true" value="#{MessageBean.a}"
/><br><br>
<h:inputSecret id="pwd" required="true" value="#{MessageBean.b}"
/><br>
<h:commandButton id="submit" value="Submit"/><br />
<h:messages showDetail="false" showSummary="true" layout="table"/>
</h:form>
</body>
</html>
</f:view>

Rendered Output :
If these input text field is not filled by the user and submit is pressed then the error messages
are flashed for this component to warn that these are the required fields to be filled. It shows
that these can't be left blank because "required" field is set to "true" for these fields. So the
output is shown below if these fields are not filled :

Html Source Code :


<html>
<body>
<form id="_id0" method="post"
action="/htmltag/pages/messages.jsf" enctype="application/x-
www-form-urlencoded">
Enter name and password below :<br>
<input id="_id0:name" type="text" name="_id0:name"
value="" /><br><br>
<input id="_id0:pwd" type="password" name="_id0:pwd"
value="" /><br>
<input id="_id0:submit" type="submit"
name="_id0:submit" value="Submit" /><br />
<table></table>
<input type="hidden" name="_id0" value="_id0" />
</form>
</body>
</html>

This messages tag contains most of the attributes common to the message tag. Only few are
different like layout attribute. All are summarized below :
• id : It is the component identifier that must be unique in the closest container.
• binding : It takes the value binding expression that is used to link the component to the
property of the backing bean.
• rendered : Its a boolean attribute. It determines whether this component should be
rendered or not.
• for : This is the required attribute for the component. It takes the id for a component.
message tag displays the message for this component whose id has been specified in for
attribute.
• showSummary : Its a boolean flag. Its default value is true. It is used to determine
whether the summary part of the message should be displayed or not.
• showDetail :Its a boolean flag. Its default value is true. It is used to determine whether
detail messages should be idisplayed or not.
• globalOnly : Its a boolean flag. Its default value is true. It is used to determine whether
global messages (which are without IDs) should be displayed or not.
• dir : It is used to set the direction of the text to be displayed. It can take two values
LTR(left to right) and RTL (right to left).
• lang : It is used to set the base language of the component when displayed.
• style : It is used to set the CSS style definition for the component.
• title : It is the standard html attribute.It is used to set the tooltip text for this component.
• styleClass : It is corresponding to html "class" attribute. It is used to set the CSS class for
the component.
• onclick : Script to be invoked when the element is clicked.
• ondblclick : It is used for Java Script code to be invoked when the element is double-
clicked.
• onmousedown : It is used for Java Script code to be invoked when the pointing device is
pressed over this element.
• onmouseup : It is used for Java Script code to be invoked when the pointing device is
released over this element.
• onmouseover : It is used for Java Script code to be invoked when the pointing device is
moved into this element.
• onmousemove : It is used for Java Script code to be invoked when the pointing device is
moved while it is in this element.
• onmouseout : It is used for Java Script code to be invoked when the pointing device is
moves out of this element.
• onkeypress : It is used for Java Script code to be invoked when a key is pressed over this
element.
• onkeydown : It is used for Java Script code to be invoked when a key is pressed down
over this element.
• onkeyup : It is used for Java Script code to be invoked when a key is released over this
element.
• infoClass : This is to determine the CSS class to be applied to information message.
• infoStyle : This is to determine the CSS style to be applied to information message.
• warnClass : This is to determine the CSS class to be applied for warning message.
• warnStyle : This is to determine the CSS style to be applied for warning message.
• errorClass : This is to determine the CSS class to be applied to error message.
• errorStyle : This is to determine the CSS style to be applied to error message.
• fatalClass : This is to determine the CSS class to be applied to fatal message.
• fatalStyle : This is to determine the CSS style to be applied to fatal message.
• layout : This is used to layout the error messages. It can take two values "table" and
"list". Its default value is "list".
• tooltip : It is a boolean attribute. It is used to determine whether to show the summary
message in a tooltip or not.

JSF outputFormat Tag

This section illustrates you about the JSF outputFormat tag. This tag is used for showing
output with the parameterized text that facility allows you to customize the appearance of the
text using CSS styles also. This tag value has been parameterized by using the JSF Core
param tag what you can learn after some sections, under the outputFormat tag.
Here, an example is also provided for the best illustration about the JSF outputFormat tag.
You will seen in the following example that value of the tag is "Hello, {0} !". Following
program will show the output like "Hello, chandan !" because "Hello, " already mentioned as
the value of the param tag that has been calling in the outputFormat tag by passing parameter
like "{0}".
You can show the output text from other resources by mentioning the backing bean value in
param tag.
Code Description:
<%@ page contentType="text/html" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<f:view>
<html>
<head><title>jsf h:outputFormat example</title></head>

<body>
<h:outputFormat value="Hello, {0} !">
<f:param value="chandan"/>
</h:outputFormat>
</body>
</html>
</f:view>

Rendered Output:
This is the image of the rendered output for the above mentioned JSF program when it is run
on the browser.

HTML Source Code:


Browser generates html code for your JSF proram like:
<html>
<head><title>jsf h:outputFormat example</title></head>

<body>
Hello, chandan !
</body>
</html>

All attributes of this tag are explained as follows:


• converter: This attribute sets a converter instance to be registered for the component.
This instance must match the converter-id value of a converter element that is defined in
the faces-config.xml file.
• escape: This attribute sets a boolean flag value that determines if sensitive HTML and
XML characters should be escaped in the output generated by the component. It's default
value is "true".
• id: This attribute sets the identification of the component uniquely. The value of the
attribute must be unique in the closest.
• rendered: This attribute take a boolean flag value that indicates the component whether
or not should be rendered in the view.
• style: If you want ot add any CSS with the component then you can put the style as the
value of the attribute. Added CSS will be applied on for the component.
• styleClass: This attribute holds the CSS class name which is defined in the external style
sheet.
• title: This attribute holds a string value that is shown as a tool-tip text of a component or
element.
• value: This attribute sets the current value for the component.
JSF outputLabel Tag

This is the outputLabel tag which show the text labeled with the specific component created in
your application. This is tag is used under the specific JSF html tag for creating a component
because the outputLabel tag is only used for a component.

Code Description:
<%@ page contentType="text/html" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<f:view>
<html>
<head><title>jsf h:outputLabel example</title></head>
<body>
<h:inputText id="name">
<h:outputLabel for="name" value="Enter your name: "/>
</h:inputText>
</body>
</html>
</f:view>

Above code creates a output label having text "Enter your name: " for a text box as you see in
the following output image.
Rendered Output:
Following code is the browser generated html code regarding the above used JSF code of the
program.
HTML Source Code:
<html>
<head><title>jsf h:outputLabel example</title></head>

<body>
<label for="name">Enter your name: </label>
<input id="name" type="text" name="name" />
</body>
</html>

All attributes of the JSF HTML outputLabel tag are explained as follows:
• accesskey: This is an attribute of the outputLink tag that sets the key by pressing that key
you can transfer the focus on the specific element or a component.
• binding: This attribute sets or gets values from the property of a backing bean by the
value-binding expression accepted by the attribute of the outputLink tag.
• converter: This attribute sets a converter instance to be registered for the component.
This instance must match the converter-id value of a converter element that is defined in
the faces-config.xml file.
• dir: This attribute sets the direction of the text. Value of the attribute is "LTR" means
left-to-right and "RTL" means right-to-left.
• for: This attribute sets the component identification for which it has to be used.
• id: This attribute sets the identification of the component uniquely. The value of the
attribute must be unique in the closest.
• lang: This attribute sets language code for using in the markup generated by the
component.
• onblur: This attribute sets JavaScript code to execute when the component loses the
focus.
• onclick: This attribute sets JavaScript code to execute when the component is clicked.
• ondblclick: This attribute sets JavaScript code to execute when the component is double
clicked.
• onfocus: This attribute sets JavaScript code to execute when the component receives the
focus.
• onkeydown: This attribute sets JavaScript code to execute when a key is pressed down
over the component.
• onkeypress: This attribute sets JavaScript code to execute when a key is pressed or
released over the component.
• onkeyup: This attribute sets JavaScript code to execute when a key is released over the
component.
• onmousedown: This attribute sets JavaScript code to execute when the mouse pointer is
pressed over the component.
• onmousemove: This attribute sets JavaScript code to execute when the mouse pointer is
moved within the component.
• onmouseout: This attribute sets JavaScript code to execute when the mouse pointer is
moved away from the element or the component.
• onmouseover: This attribute sets JavaScript code to execute when the mouse pointer is
moved onto the component.
• onmouseup: This attribute sets JavaScript code to execute when the mouse pointer is
released over the component.
• rendered: This attribute take a boolean flag value that indicates the component whether
or not should be rendered in the view.
• required: This attribute takes a boolean flag value that determines whether a user will
enter a value in the field before the submission of the form or not.
• style: If you want ot add any CSS with the component then you can put the style as the
value of the attribute. Added CSS will be applied on for the component.
• styleClass: This attribute holds the CSS class name which is defined in the external style
sheet.
• tabindex: This attribute sets the tab index for the component. When you press the TAB
key then the component will be focused after focusing all those components whose tab
index is less than the component.
• title: This attribute holds a string value that is shown as a tool-tip text of a component or
element.
• value: This attribute sets the current value for the component.

JSF outputLink Tag


This is the outputLink which show the output text holding a link of a page or a website
location. This link is similar from the link created by the JSF commandLink tag text. But the
main difference between the commandLink tag and the outputLink tag is as follows:
The outputLink tag is used for the direct navigation from the current page to another page or a
website while the commandLink tag is also used for passing values to the faces-config.xml file
to navigate another page of your application by specifying the location of the page in faces-
config.xml file. Code for the outputLink has been given as follows:
Code Description:
<%@ page contentType="text/html" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<f:view>
<html>
<head><title>jsf h:outputLink example</title></head>

<body>
<h:outputLink value="index.jsf"><h:outputText value="Go
for another page."/></h:outputLink>
</body>
</html>
</f:view>

Above code will display a hypertext with the link of the anotherpage.jsp that exists in the
same directory. Here, you will see the mentioned file has ".jsf" extension because the value of
the url-pattern attribute is *.jsf like <url-patter>*.jsf</url-pattern> in the web.xml file as
you can see. If you mention the file name with the jsf extension for the jsp page, controller
understand itself by reading the value of the url-pattern attribute of the web.xml file.
Rendered Result:

HTML Source Code:


<html>
<head><title>jsf h:outputLink example</title></head>

<body>
<a href="anotherpage.jsf">Go for another page.</a>
</body>
</html>
All attributes of the outputLink tag are explained below:
• accesskey: This is an attribute of the outputLink tag that sets the key by pressing that key
you can transfer the focus on the specific element or a component.
• binding: This attribute sets or gets values from the property of a backing bean by the
value-binding expression accepted by the attribute of the outputLink tag.
• charset: This attribute sets the character encoding for the document linked to by the
hyperlink.
• coords: When you use the link with a client-side image map then this attribute sets the
position and shape of the spot on screen. Whatever has to be viewed.
• converter: This attribute sets a converter instance to be registered for the component.
This instance must match the converter-id value of a converter element that is defined in
the faces-config.xml file.
• dir: This attribute sets the direction of the text. Value of the attribute is "LTR" means
left-to-right and "RTL" means right-to-left.
• hreflang: This attribute sets the language for the document linked to by the hyperlink.
• id: This attribute sets the value to identify the component uniquely. It's value will be
unique within the closest container.
• lang: This attribute sets language code for using in the markup generated by the
component.
• onblur: This attribute sets JavaScript code to execute when the component loses the
focus.
• onclick: This attribute sets JavaScript code to execute when the component is clicked.
• ondblclick: This attribute sets JavaScript code to execute when the component is double
clicked.
• onfocus: This attribute sets JavaScript code to execute when the component receives the
focus.
• onkeydown: This attribute sets JavaScript code to execute when a key is pressed down
over the component.
• onkeypress: This attribute sets JavaScript code to execute when a key is pressed or
released over the component.
• onkeyup: This attribute sets JavaScript code to execute when a key is released over the
component.
• onmousedown: This attribute sets JavaScript code to execute when the mouse pointer is
pressed over the component.
• onmousemove: This attribute sets JavaScript code to execute when the mouse pointer is
moved within the component.
• onmouseout: This attribute sets JavaScript code to execute when the mouse pointer is
moved away from the element or the component.
• onmouseover: This attribute sets JavaScript code to execute when the mouse pointer is
moved onto the component.
• onmouseup: This attribute sets JavaScript code to execute when the mouse pointer is
released over the component.
• rel: This attribute identifies the relationship from the current document to the anchor
specified by the hyperlink. It's value is link types separated by space.
• rev: This attribute identifies the reverse link from the anchor specified by the hyperlink
to the current document. It's value is link types separated by space.
• rendered: This attribute take a boolean flag value that indicates the component whether
or not should be rendered in the view.
• shape: This attribute sets the shape of the hotspot for viewing on the screen during the
client side image mapping. It's some valid value is "rect" for the rectangular region,
"default" for the entire region, "circle" for the circular region and "poly" for the
polygonal region.
• style: If you want ot add any CSS with the component then you can put the style as the
value of the attribute. Added CSS will be applied on for the component.
• styleClass: This attribute holds the CSS class name which is defined in the external style
sheet.
• tabindex: This attribute sets the tab index for the component. When you press the TAB
key then the component will be focused after focusing all those components whose tab
index is less than the component.
• target: This attribute set the identification of a frame in which the resource has to be
displayed that is linked to by the hyperlink.
• title: This attribute holds a string value that is shown as a tool-tip text of a component or
element.
• type: This attribute sets the content type of the resource linked to by the hyperlink.
• value: This attribute sets the value i.e. the "href" value that has to be linked from the
current document to by the hyperlink.
JSF outputText Tag

This is the section in which you can learn more about the tag named outputText tag. This tag
is used for creating component for displaying formatted output as text.
Here, you will get an example with complete source code that can be copied in your
application for creating a JSF component that show the output of your program.

Code Description:
<%@ page contentType="text/html" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<f:view>
<html>
<head><title>jsf h:message example</title></head>

<body>
<b><h:outputText value="This is the output text." /></b>
</body>
</html>
</f:view>

Above program shows the output text "This is the output text." that is specified as the value
of the JSF HTML tag outputText.
Rendered Result:

HTML Source Code:


<html>
<head><title>jsf h:message example</title></head>

<body>
<b>This is the output text.</b>
</body>
</html>

All attributes of the outputText tag are explained as follows:


• binding: This attribute accepts a value-binding expression linked to a property in a
backing bean.
• converter: This attribute sets a converter instance to be registered for the component.
This instance must match the converter-id value of a converter element that is defined in
the faces-config.xml file.
• escape: This attribute sets a boolean flag value that determines if sensitive HTML and
XML characters should be escaped in the output generated by the component. It's default
value is "true".
• id: The value of this attribute identifies the component uniquely. So, value of the id
attribute must be unique in the closest container.
• rendered: This attribute sets a boolean flag value that determines the component should
be whether or not rendered in the view.
• style: If you want ot add any CSS with the component then you can put the style as the
value of the attribute. Added CSS will be applied on for the component.
• styleClass: This attribute holds the CSS class name which is defined in the external style
sheet.
• title: This attribute holds a string value that is shown as a tool-tip text of a component or
element.
• value: This attribute sets the current value for the component.
JSF panelGrid Tag

This tag is used create compound component that is used to layout other components. This tag
renders html table with specified no. of columns. Children of this element are rendered in cells
of the columns of the table. This tag helps to construct the table which can automatically arrange
the elements in cells of the table of specified columns. Suppose, we have specified no. of
columns to 3 and we have taken 5 elements then these elements will get automatically arranged
in two rows (3 elements in 3 columns consecutively in the the first row and other 2 in the second
row in the same manner. So last two elements will be visible in two columns and third will be
blank. For more stylish and customized appearance CSS can be used. By default the no. of
columns is "1". The no of rows is decided by the no. of elements to display in the specified no. of
columns.

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

<f:view>
<html>
<body>
<h:form>
<h:panelGrid columns="3" border="1" rules="all"
title="This is panelGrid demo">
<f:facet name="header">
<h:outputText value="Fill Numbers Below"/>
</f:facet>
<h:inputText/>
<h:inputText/>
<h:inputText/>
<h:inputText/>
<h:inputText/>
<h:inputText/>
<h:inputText/>
<h:inputText/>
</h:panelGrid>
</h:form>
</body>
</html>
</f:view>
Rendered Output :

Html Source Code:


<html>
<body>
<form id="_id0" method="post"
action="/htmltag/pages/panelGrid.jsf"
enctype="application/x-www-form-urlencoded">
<table border="1" rules="all" title="This is panelGrid
demo">
<thead>
<tr><th colspan="3" scope="colgroup">Fill Numbers
Below</th></tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="_id0:_id3" /></td>
<td><input type="text" name="_id0:_id4" /></td>
<td><input type="text" name="_id0:_id5" /></td>
</tr>
<tr>
<td><input type="text" name="_id0:_id6" /></td>
<td><input type="text" name="_id0:_id7" /></td>
<td><input type="text" name="_id0:_id8" /></td>
</tr>
<tr>
<td><input type="text" name="_id0:_id9" /></td>
<td><input type="text" name="_id0:_id10" /></td>
</tr>
</tbody>
</table>
<input type="hidden" name="_id0" value="_id0"
/></form>
</body>
</html>
This tag is comprised of many attributes that are summarized below :
• id : It is the component identifier that must be unique in the closest container.
• binding : It takes the value binding expression that is used to link the component to the
property of the backing bean.
• rendered : Its a boolean attribute. Its default value is true. It determines whether this
component should be rendered or not.
• columns : This is used to specify the no. of columns in the grid.
• border : This is used to set the width of the border.
• bgcolor : This is used to set the background color of the table.
• cellpadding : This is used to set the space between the content and the border of the cell.
• cellspacing : This is used to set the space between the cells of the table.
• frame : This is used to specify the part of the frame, surrounding the table, will be
visible.
• rules : This specifies which line between the cells will be appear in the table. It can take
some values :
1) none no rules (This is the default value.)
2) groups between row groups
3) rows between rows only
4) cols between columns only
5) all between rows and columns
• summary : This can be used to provide the summary of the table.
• width : This can be used to specify the width of the table either in pixel or percentage.
• columnClasses : This is used to specify the comma seperated list of CSS style classes to
be applied on the columns of the table.
• headerClass : This is used to specify the spaces seperated list of CSS style classes to be
applied on the header of the table.
• footerClass : This is used to specify the spaces seperated list of CSS style classes to be
applied on the footer of the table.
• rowClasses : This is used to specify the comma seperated list of CSS style classes to be
applied on the rows of the table.
• dir : It is used to set the direction of the text to be displayed. It can take two values
LTR(left to right) and RTL (right to left).
• lang : It is used to set the base language of the component when displayed.
• style : It is used to set the CSS style definition for the component.
• title : It is the standard html attribute.It is used to set the tooltip text for this component.
• styleClass : It is used to set the CSS class for the component.
• onclick : Script to be invoked when the element is clicked.
• ondblclick : It is used for Java Script code to be invoked when the element is double-
clicked.
• onmousedown : It is used for Java Script code to be invoked when the pointing device is
pressed over this element.
• onmouseup : It is used for Java Script code to be invoked when the pointing device is
released over this element.
• onmouseover : It is used for Java Script code to be invoked when the pointing device is
moved into this element.
• onmousemove : It is used for Java Script code to be invoked when the pointing device is
moved while it is in this element.
• onmouseout : It is used for Java Script code to be invoked when the pointing device is
moves out of this element.
• onkeypress : It is used for Java Script code to be invoked when a key is pressed over this
element.
• onkeydown : It is used for Java Script code to be invoked when a key is pressed down
over this element.
• onkeyup : It is used for Java Script code to be invoked when a key is released over this
element.
JSF panelGroup Tag

This is used to create a component that acts as a container to group a set of components. All
these components are under one component or can say one parent. So this can be useful when we
want to nest two or more components into one parent panelGrid column. If we want to render
two components without using this tag then these will be rendered in separate columns. This
component renders its all children and count them as one component. So this fact of this tag can
be useful for us in the case where a component allows only one child component.The program
given below will make you clear this concept.
Code Description :
<%@ taglib uri="http://java.sun.com/jsf/html"
prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core"
prefix="f"%>

<f:view>
<html>
<body>
<h:form>
<h:panelGrid columns="3" border="1" rules="all"
title="This is panelGroup demo">
<f:facet name="header">
<h:outputText value="Submit Detail"/>
</f:facet>
<h:inputText/>
<h:inputText/>
<h:inputText/>
<h:inputText/>
<h:inputText/>
<h:inputText/>
<h:inputText/>
<h:inputText/>
<f:facet name="footer">
<h:panelGroup>
<h:outputText value="Leave Comment Here :" />
<h:inputText/>
<h:outputText value="Submit" />
<h:commandButton value="SUBMIT" />
</h:panelGroup>
</f:facet>
</h:panelGrid>
</h:form>
</body>
</html>
</f:view>
Rendered Output : In the above code we have taken 4 components in footer facet component.
We have used panelGroup tag to render these 4 components in a single column. It happened
because colspan has been set to 3 i.e. no of columns.

Html Source Code:


<html>
<body>
<form id="_id0" method="post"
action="/htmltag/pages/panelGroup.jsf"
enctype="application/x-www-form-urlencoded">
<table border="1" rules="all" title="This is panelGroup
demo">
<thead>
<tr><th colspan="3" scope="colgroup">Submit
Detail</th></tr>
</thead>
<tfoot>
<tr><td colspan="3">Leave Comment Here :<input
type="text" name="_id0:_id13" />Submit<input
type="submit" name="_id0:_id15" value="SUBMIT"
/></td></tr>
</tfoot>
<tbody>
<tr>
<td><input type="text" name="_id0:_id3" /></td>
<td><input type="text" name="_id0:_id4" /></td>
<td><input type="text" name="_id0:_id5" /></td>
</tr>
<tr>
<td><input type="text" name="_id0:_id6" /></td>
<td><input type="text" name="_id0:_id7" /></td>
<td><input type="text" name="_id0:_id8" /></td>
</tr>
<tr>
<td><input type="text" name="_id0:_id9" /></td>
<td><input type="text" name="_id0:_id10" /></td>
</tr>
</tbody>
</table>
<input type="hidden" name="_id0" value="_id0" /></form>
</body>
</html>
This tag is comprised of many attributes that are summarized below :
• id : It is the component identifier that must be unique in the closest container.
• binding : It takes the value binding expression that is used to link the component to the
property of the backing bean.
• rendered : Its a boolean attribute. Its default value is true. It determines whether this
component should be rendered or not.
• style : It is used to set the CSS style definition for the component.
• styleClass : It is used to set the CSS class for the component.
JSF selectBooleanCheckbox Tag

This section explains you creating checkbox by JSF tag. selectBooleanCheckbox tag is used to
create checkbox. This tag renders an html "input" tag whose type is set to "checkbox" and
"name" is set to "id". If the "value" of this component is set to "true" then a checked checkbox
is rendered. This is used when we want to give an option to the user to select or deselect.
Code Description :
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<f:view>
<html>
<body>
<h:form>
<h:selectBooleanCheckbox id="checkbox" value="true"
title="click it to select or deselect"/>
<h:outputText value="Want to participate?"/>
</h:form>
</body>
</html>
</f:view>
Rendered Output : In the above code value is set to true so checkbox is rendered as checked.
On moving the mouse pointer to the chenkbox element a tooltip pops up that is the text written
in title attribute.

Html Source Code :


<html>
<body>
<form id="_id0" method="post" action="/htmltag/pages
/selectBooleanCheckbox.jsf" enctype="application/x-www-
form-urlencoded">
<input id="_id0:checkbox" type="checkbox"
name="_id0:checkbox" checked title="click it to select or
deselect" />
Want to participate?
<input type="hidden" name="_id0" value="_id0" />
</form>
</body>
</html>
This tag contains some attributes that are described below :
• id : It is the component identifier that must be unique in the closest container.
• binding : It takes the value binding expression that is used to link the component to the
property of the backing bean.
• rendered : Its a boolean attribute. Its default value is true. It determines whether this
component should be rendered or not.
• value : This is to set the current value of the component.
• converter : This specifies the converter for the component. This can be static value or
EL expression .
• immediate : Its a boolean attribute. It is used to identify during which phase value
change event should occur. If this attribute is set to true then in place of firing the event
during the process validation phase, these event are sent immadiately at the end of apply
request values phase.
• required : Its a boolean attribute. It indicates that its value is required by the user before
the submission of the form to the server.
• validator : It takes the method binding expression. This expression represents the
validator method. This method is called at the time of validation of the component.
• valueChangeListener : This also takes a method binding expression. This expression
represents value change listener method. This method will be called when new value is
set for this component.
• dir : It is used to set the direction of the text to be displayed. It can take two values
LTR(left to right) and RTL (right to left).
• lang : It is used to set the base language of the component when displayed.
• style : It is used to set the CSS style definition for the component.
• title : It is the standard html attribute.It is used to set the tooltip text for this component.
• styleClass : It is used to set the CSS class for the component.
• onclick : Script to be invoked when the element is clicked.
• ondblclick : It is used for Java Script code to be invoked when the element is double-
clicked.
• onmousedown : It is used for Java Script code to be invoked when the pointing device is
pressed over this element.
• onmouseup : It is used for Java Script code to be invoked when the pointing device is
released over this element.
• onmouseover : It is used for Java Script code to be invoked when the pointing device is
moved into this element.
• onmousemove : It is used for Java Script code to be invoked when the pointing device is
moved while it is in this element.
• onmouseout : It is used for Java Script code to be invoked when the pointing device is
moves out of this element.
• onkeypress : It is used for Java Script code to be invoked when a key is pressed over this
element.
• onkeydown : It is used for Java Script code to be invoked when a key is pressed down
over this element.
• onkeyup : It is used for Java Script code to be invoked when a key is released over this
element.
• accesskey : This is standard html attribute. It is used to set the access key for the element
which is used to send the focus to the element when pressed.
• alt : This is used as an alternate text that is displayed when browser is not able to display
the element.
• disabled : Its a boolean attribute. This is used to disable the element to receive focus,
when it is set to true.
• onblur : It is used to set the java script code to execute when focus is lost from the
element.
• onfocus : It is used to set the java script code to execute when focus is received by the
element.
• onchange : It is used to set the java script code to execute when element is modified.
• onselect : It is used to set the java script code to execute when element is modified
• readonly : Its a boolean attribute. It is used to indicate the user that its value can't be
modified, if it is set to true.
• tabindex : This is a standard html attribute. It is used to set the order of receiving the
focus on the movement of TAB key by the user.
JSF selectManyCheckbox Tag

This section is to describe you selectManyCheckbox tag of JSF. It is used to provide the user
to select many items from a list of options. The user can select one or more options. This
supports two layouts "lineDirection" and "pageDirection".layout determines whether the
chenkboxes are laid out horizontally or vertically. lineDirection is the default layout.
lineDirection sets the checkboxes in the horizontal direction of the page and pageDirection is
used to set the checkboxes in vertical direction of the page. f:selectItem or f:selectItems are
used to provide a list of available options. selectManyCheckbox renders these options in a
table where each option is set to one cell. Each cell contains the checkbox and label of the
option. The value attribute of this tag must be value binding expression. This value can be
bound to data type of java like primitive array, object array, List.

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

<f:view>
<html>
<body>
<h:form>
<h:outputText value="Click one or more options below :"/>
<h:selectManyCheckbox id="smc"
value="#{TableBean.perInfoAll}" border="1"
disabled="false"
title="this is 'selectManyCheckbox' demo"
layout="lineDirection">
<f:selectItem id="si1" itemLabel="Thums Up" itemValue="11"
/>
<f:selectItem id="si2" itemLabel="Limca" itemValue="22" />
<f:selectItem id="si3" itemLabel="Pepsi" itemValue="33" />
<f:selectItem id="si4" itemLabel="Sprite" itemValue="44" />
<f:selectItem id="si5" itemLabel="Frooti" itemValue="55" />
<f:selectItem id="si6" itemLabel="Coca-Cola" itemValue="66"
/>
</h:selectManyCheckbox><br>
</h:form>
</body>
</html>
</f:view>
Rendered Output :

Html Source Code:


<html>
<body>
<form id="_id0" method="post" action="/htmltag/pages/selectManyCheckbox.jsf"
enctype="application/x-www-form-urlencoded">
Click one or more options below :
<table border="1" id="_id0:smc"><tr><td>
<label><input name="_id0:smc" value="11" type="checkbox" border="1" title=
"this is 'selectManyCheckbox' demo"> Thums Up</input></label></td>
<td>
<label><input name="_id0:smc" value="22" type="checkbox" border="1" title=
"this is 'selectManyCheckbox' demo"> Limca</input></label></td>
<td>
<label><input name="_id0:smc" value="33" type="checkbox" border="1" title=
"this is 'selectManyCheckbox' demo"> Pepsi</input></label></td>
<td>
<label><input name="_id0:smc" value="44" type="checkbox" border="1" title=
"this is 'selectManyCheckbox' demo"> Sprite</input></label></td>
<td>
<label><input name="_id0:smc" value="55" type="checkbox" border="1" title=
"this is 'selectManyCheckbox' demo"> Frooti</input></label></td>
<td>
<label><input name="_id0:smc" value="66" type="checkbox" border="1" title=
"this is 'selectManyCheckbox' demo"> Coca-Cola</input></label>
</td>
</tr>
</table><br>
<input type="hidden" name="_id0" value="_id0" /></form>
</body>
</html>
This tag is comprised of many attributes that are summarized below :
• id : It is the component identifier that must be unique in the closest container.
• layout : This attribute is used to set the components either vertically or horizontally by
two values "lineDirection" and "pageDirection" respectively.This attribute takes
"lineDirection" value bydefault.
• enabledClass : This attribute is used to set the CSS class to the label of disabled choices.
• disabledClass : This attribute is used to set the CSS class to the label of enabled choices.
• binding : It takes the value binding expression that is used to link the component to the
property of the backing bean.
• rendered : Its a boolean attribute. Its default value is true. It determines whether this
component should be rendered or not.
• value : This is to set the current value of the component.
• converter : This specifies the converter for the component. This can be static value or EL
expression .
• immediate : Its a boolean attribute. It is used to identify during which phase value
change event should occur. If this attribute is set to true then in place of firing the event
during the process validation phase, these event are sent immadiately at the end of apply
request values phase.
• required : Its a boolean attribute. It indicates that its value is required by the user before
the submission of the form to the server. If it is set to true and value is not provided then
an error message comes.
• validator : It takes the method binding expression. This expression represents the
validator method. This method is called at the time of validation of the component.
• valueChangeListener : This also takes a method binding expression. This expression
represents value change listener method. This method will be called when new value is
set for this component.
• border : It is used to set the border width of the table containing these choices.
• dir : It is used to set the direction of the text to be displayed. It can take two values
LTR(left to right) and RTL (right to left).
• lang : It is used to set the base language of the component when displayed.
• style : It is used to set the CSS style definition for the component.
• title : It is the standard html attribute.It is used to set the tooltip text for this component.
• styleClass : It is used to set the CSS class for the component.
• onclick : Script to be invoked when the element is clicked.
• ondblclick : It is used for Java Script code to be invoked when the element is double-
clicked.
• onmousedown : It is used for Java Script code to be invoked when the pointing device is
pressed over this element.
• onmouseup : It is used for Java Script code to be invoked when the pointing device is
released over this element.
• onmouseover : It is used for Java Script code to be invoked when the pointing device is
moved into this element.
• onmousemove : It is used for Java Script code to be invoked when the pointing device is
moved while it is in this element.
• onmouseout : It is used for Java Script code to be invoked when the pointing device is
moves out of this element.
• onkeypress : It is used for Java Script code to be invoked when a key is pressed over this
element.
• onkeydown : It is used for Java Script code to be invoked when a key is pressed down
over this element.
• onkeyup : It is used for Java Script code to be invoked when a key is released over this
element.
• accesskey : This is standard html attribute. It is used to set the access key for the element
which is used to send the focus to the element when pressed.
• alt : This is used as an alternate text that is displayed when browser is not able to display
the element.
• disabled : Its a boolean attribute. This is used to disable the element to receive focus,
when it is set to true.
• onblur : It is used to set the java script code to execute when focus is lost from the
element.
• onfocus : It is used to set the java script code to execute when focus is received by the
element.
• onchange : It is used to set the java script code to execute when element is modified.
• onselect : It is used to set the java script code to execute when element is modified
• readonly : Its a boolean attribute. It is used to indicate the user that its value can't be
modified, if it is set to true.
• tabindex : This is a standard html attribute. It is used to set the order of receiving the
focus on the movement of TAB key by the user.
JSF selectManyListbox Tag

This section is dedicated to describe you about selectManyListbox tag. This lets you select
more than one options from a set of available options. It renders an html "select" element of
specified size with "multiple" attribute. size is used to specify how many options are to be
displayed at a time. If size is not specified then it displays all the choices i.e. its default value
is equal to no. of available options. If we set this size to "1" then drop down list is rendered.
Instead of doing this we can use "selectManyMenu" tag of JSF. If size is specified less than
the total no. of available options then scroll bar is rendered which can be used to see all the
options by moving it. Options are added by the use of f:selectItem or f:selectItems.
Code Description :
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<f:view>
<html>
<body>
<h:form>
<h:selectManyListbox id="subscriptions" value="#{TableBean.perInfoAll}"

title="select one or more options by pressing the control key" size="3">


<f:selectItem id="si1" itemLabel="Thums Up" itemValue="11" />
<f:selectItem id="si2" itemLabel="Limca" itemValue="22" />
<f:selectItem id="si3" itemLabel="Pepsi" itemValue="33" />
<f:selectItem id="si4" itemLabel="Sprite" itemValue="44" />
<f:selectItem id="si5" itemLabel="Frooti" itemValue="55" />
<f:selectItem id="si6" itemLabel="Coca-Cola" itemValue="66" />
</h:selectManyListbox>
</h:form>
</body>
</html>
</f:view>
Rendered Output :
Html Source Code:
<html>
<body>
<form id="_id0" method="post" action="/htmltag/pages/selectManyListbox.jsf"

enctype="application/x-www-form-urlencoded">
<select id="_id0:subscriptions" name="_id0:subscriptions" multiple size="3"
title="select one or more options by pressing the control key">
<option value="11">Thums Up</option>
<option value="22">Limca</option>
<option value="33">Pepsi</option>
<option value="44">Sprite</option>
<option value="55">Frooti</option>
<option value="66">Coca-Cola</option>
</select>
<input type="hidden" name="_id0" value="_id0" />
</form>
</body>
</html>
This tag can use some attributes that are useful in different places for different purpose. Here
is the list of attributes :
• id : This attribute is used to uniquely identify the element within the closest container.
• size : It is used to determine how many options have to be shown at a time from the list
of available options. If it is not specified then all are shown. If size is set to less than the
number of available options then scroll bar is rendered.
• enabledClass : This attribute is used to set the CSS class to the label of disabled choices.
• disabledClass : This attribute is used to set the CSS class to the label of enabled choices.
• binding : It takes the value binding expression that is used to link the component to the
property of the backing bean.
• rendered : Its a boolean attribute. Its default value is true. It determines whether this
component should be rendered or not.
• value : This is to set the current value of the component.
• converter : This specifies the converter for the component. This can be static value or EL
expression .
• immediate : Its a boolean attribute. It is used to identify during which phase value
change event should occur. If this attribute is set to true then in place of firing the event
during the process validation phase, these event are sent immadiately at the end of apply
request values phase.
• required : Its a boolean attribute. It indicates that its value is required by the user before
the submission of the form to the server. If it is set to true and value is not provided then
an error message comes.
• validator : It takes the method binding expression. This expression represents the
validator method. This method is called at the time of validation of the component.
• valueChangeListener : This also takes a method binding expression. This expression
represents value change listener method. This method will be called when new value is
set for this component.
• dir : It is used to set the direction of the text to be displayed. It can take two values
LTR(left to right) and RTL (right to left).
• lang : It is used to set the base language of the component when displayed.
• style : It is used to set the CSS style definition for the component.
• title : It is the standard html attribute.It is used to set the tooltip text for this component.
• styleClass : It is used to set the CSS class for the component.
• onclick : Script to be invoked when the element is clicked.
• ondblclick : It is used for Java Script code to be invoked when the element is double-
clicked.
• onmousedown : It is used for Java Script code to be invoked when the pointing device is
pressed over this element.
• onmouseup : It is used for Java Script code to be invoked when the pointing device is
released over this element.
• onmouseover : It is used for Java Script code to be invoked when the pointing device is
moved into this element.
• onmousemove : It is used for Java Script code to be invoked when the pointing device is
moved while it is in this element.
• onmouseout : It is used for Java Script code to be invoked when the pointing device is
moves out of this element.
• onkeypress : It is used for Java Script code to be invoked when a key is pressed over this
element.
• onkeydown : It is used for Java Script code to be invoked when a key is pressed down
over this element.
• onkeyup : It is used for Java Script code to be invoked when a key is released over this
element.
• accesskey : This is standard html attribute. It is used to set the access key for the element
which is used to send the focus to the element when pressed.
• disabled : Its a boolean attribute. This is used to disable the element to receive focus,
when it is set to true.
• onblur : It is used to set the java script code to execute when focus is lost from the
element.
• onfocus : It is used to set the java script code to execute when focus is received by the
element.
• onchange : It is used to set the java script code to execute when element is modified.
• onselect : It is used to set the java script code to execute when element is modified
• readonly : Its a boolean attribute. It is used to indicate the user that its value can't be
modified, if it is set to true.
• tabindex : This is a standard html attribute. It is used to set the order of receiving the
focus on the movement of TAB key by the user.
JSF selectManyMenu Tag

In this section "selectManyMenu" tag will be discussed. This is used to select more than one
items from a set of options. This renders an html "select" element which contains "multiple"
attribute with size "1". This renders the menu of options where only one is visible at a time.
The difference between "selectManyListbox" and "selectManyMenu" is that listbox can be
set to any size and menu is always set to size "1". Options can be added by the use of
f:selectItem or f:selectItems. This tag can render different output in different browsers. In
Internet Explorer browser user can select the items by scrolling the arrow icon up and down
but its not the case for Mozilla or Netscape browser. In the later case this menu looks like an
input text box but many of the items can be selected.
Code Description :
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<f:view>
<html>
<body>
<h:form>
<h:selectManyMenu id="smm" value="#{TableBean.perInfoAll}"
title="select one or more items">
<f:selectItem id="si1" itemLabel="Thums Up" itemValue="11" />
<f:selectItem id="si2" itemLabel="Limca" itemValue="22" />
<f:selectItem id="si3" itemLabel="Pepsi" itemValue="33" />
<f:selectItem id="si4" itemLabel="Sprite" itemValue="44" />
<f:selectItem id="si5" itemLabel="Frooti" itemValue="55" />
<f:selectItem id="si6" itemLabel="Coca-Cola" itemValue="66" />
</h:selectManyMenu>
</h:form>
</body>
</html>
</f:view>

Rendered Output :
1) In Mozilla browser :

2) In Internet Explorer :

Html Source Code:


<html>
<body>
<form id="_id0" method="post"
action="/htmltag/pages/selectManyMenu.jsf"
enctype="application/x-www-form-urlencoded">
<select id="_id0:smm" name="_id0:smm" multiple
size="1" title="select one or more items">
<option value="11">Thums Up</option>
<option value="22">Limca</option>
<option value="33">Pepsi</option>
<option value="44">Sprite</option>
<option value="55">Frooti</option>
<option value="66">Coca-Cola</option>
</select>
<input type="hidden" name="_id0" value="_id0" /></form>
</body>
</html>

This tag can use some attributes that are useful in different places for different purpose. Here
is the list of attributes :
• id : This attribute is used to uniquely identify the element within the closest container.
• enabledClass : This attribute is used to set the CSS class to the label of disabled choices.
• disabledClass : This attribute is used to set the CSS class to the label of enabled choices.
• binding : It takes the value binding expression that is used to link the component to the
property of the backing bean.
• rendered : Its a boolean attribute. Its default value is true. It determines whether this
component should be rendered or not.
• value : This is to set the current value of the component.
• converter : This specifies the converter for the component. This can be static value or EL
expression .
• immediate : Its a boolean attribute. It is used to identify during which phase value
change event should occur. If this attribute is set to true then in place of firing the event
during the process validation phase, these event are sent immadiately at the end of apply
request values phase.
• required : Its a boolean attribute. It indicates that its value is required by the user before
the submission of the form to the server. If it is set to true and value is not provided then
an error message comes.
• validator : It takes the method binding expression. This expression represents the
validator method. This method is called at the time of validation of the component.
• valueChangeListener : This also takes a method binding expression. This expression
represents value change listener method. This method will be called when new value is
set for this component.
• dir : It is used to set the direction of the text to be displayed. It can take two values
LTR(left to right) and RTL (right to left).
• lang : It is used to set the base language of the component when displayed.
• style : It is used to set the CSS style definition for the component.
• title : It is the standard html attribute.It is used to set the tooltip text for this component.
• styleClass : It is used to set the CSS class for the component.
• onclick : Script to be invoked when the element is clicked.
• ondblclick : It is used for Java Script code to be invoked when the element is double-
clicked.
• onmousedown : It is used for Java Script code to be invoked when the pointing device is
pressed over this element.
• onmouseup : It is used for Java Script code to be invoked when the pointing device is
released over this element.
• onmouseover : It is used for Java Script code to be invoked when the pointing device is
moved into this element.
• onmousemove : It is used for Java Script code to be invoked when the pointing device is
moved while it is in this element.
• onmouseout : It is used for Java Script code to be invoked when the pointing device is
moves out of this element.
• onkeypress : It is used for Java Script code to be invoked when a key is pressed over this
element.
• onkeydown : It is used for Java Script code to be invoked when a key is pressed down
over this element.
• onkeyup : It is used for Java Script code to be invoked when a key is released over this
element.
• accesskey : This is standard html attribute. It is used to set the access key for the element
which is used to send the focus to the element when pressed.
• disabled : Its a boolean attribute. This is used to disable the element to receive focus,
when it is set to true.
• onblur : It is used to set the java script code to execute when focus is lost from the
element.
• onfocus : It is used to set the java script code to execute when focus is received by the
element.
• onchange : It is used to set the java script code to execute when element is modified.
• onselect : It is used to set the java script code to execute when element is modified
• readonly : Its a boolean attribute. It is used to indicate the user that its value can't be
modified, if it is set to true.
• tabindex : This is a standard html attribute. It is used to set the order of receiving the
focus on the movement of TAB key by the user.
JSF selectOneListbox Tag

This section describes you about selectOneListbox tag in detail. This is used when you have
to allow the user to select only one option from the list. Actually it renders an html "select"
element of any size and no "multiple" attribute. The choices that we have to display in the
list are shown by f:selectItem or f:selectItems. size attribute is used to set the number of
options to display at a time. If its size is not specified then it shows all the choices i.e. its
default size is equal to no. of available options. If we set size attribute to less than the total
no. of available choices then a scrollbar appears and the number of elements specified in the
size attribute are shown. We can see other options by moving the scrollbar down and up. If
size is set to "1" then drop down menu is rendered. So instead of using this strategy, its good
to use "selentOneMenu" tag provided by JSF.
Code Description :
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<f:view>
<html>
<body>
<h:form>
<h:selectOneListbox id="sol" value="TableBean.perInfoAll"
size="3" title="select one option">
<f:selectItem id="si1" itemLabel="Thums Up" itemValue="11" />
<f:selectItem id="si2" itemLabel="Limca" itemValue="22" />
<f:selectItem id="si3" itemLabel="Pepsi" itemValue="33" />
<f:selectItem id="si4" itemLabel="Sprite" itemValue="44" />
<f:selectItem id="si5" itemLabel="Frooti" itemValue="55" />
<f:selectItem id="si6" itemLabel="Coca-Cola" itemValue="66" />
</h:selectOneListbox>
</h:form>
</body>
</html>
</f:view>

Rendered Output :

Html Source Code:


<html>
<body>
<form id="_id0" method="post"
action="/htmltag/pages/selectOneListbox.jsf"
enctype="application/x-www-form-urlencoded">
<select id="_id0:sol" name="_id0:sol" size="3"
title="select one option">
<option value="11">Thums Up</option>
<option value="22">Limca</option>
<option value="33">Pepsi</option>
<option value="44">Sprite</option>
<option value="55">Frooti</option>
<option value="66">Coca-Cola</option>
</select>
<input type="hidden" name="_id0" value="_id0" />
</form>
</body>
</html>

This tag contains some attributes that can be used for different purposes. These attributes are
summarized below :
• id : This attribute is used to uniquely identify the element within the closest container.
• size : It is used to determine how many options have to be shown at a time from the list
of available options. If it is not specified then all are shown. If size is set to less than the
number of available options then scroll bar is rendered.
• enabledClass : This attribute is used to set the CSS class to the label of disabled choices.
• disabledClass : This attribute is used to set the CSS class to the label of enabled choices.
• binding : It takes the value binding expression that is used to link the component to the
property of the backing bean.
• rendered : Its a boolean attribute. Its default value is true. It determines whether this
component should be rendered or not.
• value : This is to set the current value of the component.
• converter : This specifies the converter for the component. This can be static value or EL
expression .
• immediate : Its a boolean attribute. It is used to identify during which phase value
change event should occur. If this attribute is set to true then in place of firing the event
during the process validation phase, these event are sent immadiately at the end of apply
request values phase.
• required : Its a boolean attribute. It indicates that its value is required by the user before
the submission of the form to the server. If it is set to true and value is not provided then
an error message comes.
• validator : It takes the method binding expression. This expression represents the
validator method. This method is called at the time of validation of the component.
• valueChangeListener : This also takes a method binding expression. This expression
represents value change listener method. This method will be called when new value is
set for this component.
• dir : It is used to set the direction of the text to be displayed. It can take two values
LTR(left to right) and RTL (right to left).
• lang : It is used to set the base language of the component when displayed.
• style : It is used to set the CSS style definition for the component.
• title : It is the standard html attribute.It is used to set the tooltip text for this component.
• styleClass : It is used to set the CSS class for the component.
• onclick : Script to be invoked when the element is clicked.
• ondblclick : It is used for Java Script code to be invoked when the element is double-
clicked.
• onmousedown : It is used for Java Script code to be invoked when the pointing device is
pressed over this element.
• onmouseup : It is used for Java Script code to be invoked when the pointing device is
released over this element.
• onmouseover : It is used for Java Script code to be invoked when the pointing device is
moved into this element.
• onmousemove : It is used for Java Script code to be invoked when the pointing device is
moved while it is in this element.
• onmouseout : It is used for Java Script code to be invoked when the pointing device is
moves out of this element.
• onkeypress : It is used for Java Script code to be invoked when a key is pressed over this
element.
• onkeydown : It is used for Java Script code to be invoked when a key is pressed down
over this element.
• onkeyup : It is used for Java Script code to be invoked when a key is released over this
element.
• accesskey : This is standard html attribute. It is used to set the access key for the element
which is used to send the focus to the element when pressed.
• disabled : Its a boolean attribute. This is used to disable the element to receive focus,
when it is set to true.
• onblur : It is used to set the java script code to execute when focus is lost from the
element.
• onfocus : It is used to set the java script code to execute when focus is received by the
element.
• onchange : It is used to set the java script code to execute when element is modified.
• onselect : It is used to set the java script code to execute when element is modified
• readonly : Its a boolean attribute. It is used to indicate the user that its value can't be
modified, if it is set to true.
• tabindex : This is a standard html attribute. It is used to set the order of receiving the
focus on the movement of TAB key by the user.
This section describes you about selectOneListbox tag in detail. This is used when you have
to allow the user to select only one option from the list. Actually it renders an html "select"
element of any size and no "multiple" attribute. The choices that we have to display in the
list are shown by f:selectItem or f:selectItems. size attribute is used to set the number of
options to display at a time. If its size is not specified then it shows all the choices i.e. its
default size is equal to no. of available options. If we set size attribute to less than the total
no. of available choices then a scrollbar appears and the number of elements specified in the
size attribute are shown. We can see other options by moving the scrollbar down and up. If
size is set to "1" then drop down menu is rendered. So instead of using this strategy, its good
to use "selentOneMenu" tag provided by JSF.
Code Description :
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<f:view>
<html>
<body>
<h:form>
<h:selectOneListbox id="sol" value="TableBean.perInfoAll"
size="3" title="select one option">
<f:selectItem id="si1" itemLabel="Thums Up" itemValue="11" />
<f:selectItem id="si2" itemLabel="Limca" itemValue="22" />
<f:selectItem id="si3" itemLabel="Pepsi" itemValue="33" />
<f:selectItem id="si4" itemLabel="Sprite" itemValue="44" />
<f:selectItem id="si5" itemLabel="Frooti" itemValue="55" />
<f:selectItem id="si6" itemLabel="Coca-Cola" itemValue="66" />
</h:selectOneListbox>
</h:form>
</body>
</html>
</f:view>

Rendered Output :

Html Source Code:


<html>
<body>
<form id="_id0" method="post"
action="/htmltag/pages/selectOneListbox.jsf"
enctype="application/x-www-form-urlencoded">
<select id="_id0:sol" name="_id0:sol" size="3"
title="select one option">
<option value="11">Thums Up</option>
<option value="22">Limca</option>
<option value="33">Pepsi</option>
<option value="44">Sprite</option>
<option value="55">Frooti</option>
<option value="66">Coca-Cola</option>
</select>
<input type="hidden" name="_id0" value="_id0" />
</form>
</body>
</html>

This tag contains some attributes that can be used for different purposes. These attributes are
summarized below :
• id : This attribute is used to uniquely identify the element within the closest container.
• size : It is used to determine how many options have to be shown at a time from the list
of available options. If it is not specified then all are shown. If size is set to less than the
number of available options then scroll bar is rendered.
• enabledClass : This attribute is used to set the CSS class to the label of disabled choices.
• disabledClass : This attribute is used to set the CSS class to the label of enabled choices.
• binding : It takes the value binding expression that is used to link the component to the
property of the backing bean.
• rendered : Its a boolean attribute. Its default value is true. It determines whether this
component should be rendered or not.
• value : This is to set the current value of the component.
• converter : This specifies the converter for the component. This can be static value or EL
expression .
• immediate : Its a boolean attribute. It is used to identify during which phase value
change event should occur. If this attribute is set to true then in place of firing the event
during the process validation phase, these event are sent immadiately at the end of apply
request values phase.
• required : Its a boolean attribute. It indicates that its value is required by the user before
the submission of the form to the server. If it is set to true and value is not provided then
an error message comes.
• validator : It takes the method binding expression. This expression represents the
validator method. This method is called at the time of validation of the component.
• valueChangeListener : This also takes a method binding expression. This expression
represents value change listener method. This method will be called when new value is
set for this component.
• dir : It is used to set the direction of the text to be displayed. It can take two values
LTR(left to right) and RTL (right to left).
• lang : It is used to set the base language of the component when displayed.
• style : It is used to set the CSS style definition for the component.
• title : It is the standard html attribute.It is used to set the tooltip text for this component.
• styleClass : It is used to set the CSS class for the component.
• onclick : Script to be invoked when the element is clicked.
• ondblclick : It is used for Java Script code to be invoked when the element is double-
clicked.
• onmousedown : It is used for Java Script code to be invoked when the pointing device is
pressed over this element.
• onmouseup : It is used for Java Script code to be invoked when the pointing device is
released over this element.
• onmouseover : It is used for Java Script code to be invoked when the pointing device is
moved into this element.
• onmousemove : It is used for Java Script code to be invoked when the pointing device is
moved while it is in this element.
• onmouseout : It is used for Java Script code to be invoked when the pointing device is
moves out of this element.
• onkeypress : It is used for Java Script code to be invoked when a key is pressed over this
element.
• onkeydown : It is used for Java Script code to be invoked when a key is pressed down
over this element.
• onkeyup : It is used for Java Script code to be invoked when a key is released over this
element.
• accesskey : This is standard html attribute. It is used to set the access key for the element
which is used to send the focus to the element when pressed.
• disabled : Its a boolean attribute. This is used to disable the element to receive focus,
when it is set to true.
• onblur : It is used to set the java script code to execute when focus is lost from the
element.
• onfocus : It is used to set the java script code to execute when focus is received by the
element.
• onchange : It is used to set the java script code to execute when element is modified.
• onselect : It is used to set the java script code to execute when element is modified
• readonly : Its a boolean attribute. It is used to indicate the user that its value can't be
modified, if it is set to true.
• tabindex : This is a standard html attribute. It is used to set the order of receiving the
focus on the movement of TAB key by the user.
JSF selectOneMenu Tag

This is the section where you will learn about "selectOneMenu" tag. This is used to display
the element that enables the user to select only one among the list of available options. In the
menu only one option is displayed at a time. This tag renders an html "select" element of size
"1" with no multiple attribute. So have a look on the difference between listbox and menu.
listbox can be specified of any size but menu is set to size "1" by default. The choices that
we have to display in the list are added by f:selectItem or f:selectItems.
Code Description :
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<f:view>
<html>
<body>
<h:form>
<h:selectOneMenu id="som" value="TableBean.perInfoAll"
title="select any one in this menu">
<f:selectItem id="si1" itemLabel="Thums Up" itemValue="11" />
<f:selectItem id="si2" itemLabel="Limca" itemValue="22" />
<f:selectItem id="si3" itemLabel="Pepsi" itemValue="33" />
<f:selectItem id="si4" itemLabel="Sprite" itemValue="44" />
<f:selectItem id="si5" itemLabel="Frooti" itemValue="55" />
<f:selectItem id="si6" itemLabel="Coca-Cola" itemValue="66" />
</h:selectOneMenu>
</h:form>
</body>
</html>
</f:view>

Rendered Output :

Html Source Code: Here you can see that size of the element is set to "1" in the html source
code.
<html>
<body>
<form id="_id0" method="post"
action="/htmltag/pages/selectOneMenu.jsf"
enctype="application/x-www-form-urlencoded">

<select id="_id0:som" name="_id0:som" size="1" title="select


any one in this menu"> <option value="11">Thums Up</option>
<option value="22">Limca</option>
<option value="33">Pepsi</option>
<option value="44">Sprite</option>
<option value="55">Frooti</option>
<option value="66">Coca-Cola</option>
</select>
<input type="hidden" name="_id0" value="_id0" />
</form>
</body>
</html>

This tag contains some attributes that can be used for different purposes. These attributes are
summarized below :
• id : This attribute is used to uniquely identify the element within the closest container.
• enabledClass : This attribute is used to set the CSS class to the label of disabled choices.
• disabledClass : This attribute is used to set the CSS class to the label of enabled choices.
• binding : It takes the value binding expression that is used to link the component to the
property of the backing bean.
• rendered : Its a boolean attribute. Its default value is true. It determines whether this
component should be rendered or not.
• value : This is to set the current value of the component.
• converter : This specifies the converter for the component. This can be static value or EL
expression .
• immediate : Its a boolean attribute. It is used to identify during which phase value
change event should occur. If this attribute is set to true then in place of firing the event
during the process validation phase, these event are sent immadiately at the end of apply
request values phase.
• required : Its a boolean attribute. It indicates that its value is required by the user before
the submission of the form to the server. If it is set to true and value is not provided then
an error message comes.
• validator : It takes the method binding expression. This expression represents the
validator method. This method is called at the time of validation of the component.
• valueChangeListener : This also takes a method binding expression. This expression
represents value change listener method. This method will be called when new value is
set for this component.
• dir : It is used to set the direction of the text to be displayed. It can take two values
LTR(left to right) and RTL (right to left).
• lang : It is used to set the base language of the component when displayed.
• style : It is used to set the CSS style definition for the component.
• title : It is the standard html attribute. It is used to set the tooltip text for this component.
• styleClass : It is used to set the CSS class for the component.
• onclick : Script to be invoked when the element is clicked.
• ondblclick : It is used for Java Script code to be invoked when the element is double-
clicked.
• onmousedown : It is used for Java Script code to be invoked when the pointing device is
pressed over this element.
• onmouseup : It is used for Java Script code to be invoked when the pointing device is
released over this element.
• onmouseover : It is used for Java Script code to be invoked when the pointing device is
moved into this element.
• onmousemove : It is used for Java Script code to be invoked when the pointing device is
moved while it is in this element.
• onmouseout : It is used for Java Script code to be invoked when the pointing device is
moves out of this element.
• onkeypress : It is used for Java Script code to be invoked when a key is pressed over this
element.
• onkeydown : It is used for Java Script code to be invoked when a key is pressed down
over this element.
• onkeyup : It is used for Java Script code to be invoked when a key is released over this
element.
• accesskey : This is standard html attribute. It is used to set the access key for the element
which is used to send the focus to the element when pressed.
• disabled : Its a boolean attribute. This is used to disable the element to receive focus,
when it is set to true.
• onblur : It is used to set the java script code to execute when focus is lost from the
element.
• onfocus : It is used to set the java script code to execute when focus is received by the
element.
• onchange : It is used to set the java script code to execute when element is modified.
• onselect : It is used to set the java script code to execute when element is modified
• readonly : Its a boolean attribute. It is used to indicate the user that its value can't be
modified, if it is set to true.
• tabindex : This is a standard html attribute. It is used to set the order of receiving the
focus on the movement of TAB key by the user.
JSF selectOneRadio Tag

This section is in concern with discussing about "selectOneRadio" tag. This allows the user
to select one option from a set of available options. It renders a table which contains "input"
elements of type "radio". It renders such a list of options where if you select any other option
the previous selection gets automatically deselected. This tag supports two layout
"lineDirection" and "pageDirection" for horizontal and vertical .layout determines whether
the chenkboxes are laid out horizontally or vertically. lineDirection is the default layout.
f:selectItem or f:selectItems are used to provide a list of available options.
Code Description :
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<f:view>
<html>
<body>
<h:form>
<h:selectOneRadio id="sor"
value="TableBean.perInfoAll" title="Select any one of the
choice" layout="pageDirection" border="1">
<f:selectItem id="si1" itemLabel="Thums Up" itemValue="11" />
<f:selectItem id="si2" itemLabel="Limca" itemValue="22" />
<f:selectItem id="si3" itemLabel="Pepsi" itemValue="33" />
<f:selectItem id="si4" itemLabel="Sprite" itemValue="44" />
<f:selectItem id="si5" itemLabel="Frooti" itemValue="55" />
<f:selectItem id="si6" itemLabel="Coca-Cola" itemValue="66" />
</h:selectOneRadio>

</h:form>
</body>
</html>
</f:view>

Rendered Output :

Html Source Code:


<html>
<body>
<form id="_id0" method="post"
action="/htmltag/pages/selectOneRadio.jsf"
enctype="application/x-www-form-urlencoded">
<table border="1" id="_id0:sor">
<tr><td>
<label><input type="radio" name="_id0:sor" value="11"
border="1" title="Select any one of the choice"> Thums
Up</input></label></td>
</tr>
<tr><td>
<label><input type="radio" name="_id0:sor" value="22"
border="1" title="Select any one of the choice">
Limca</input></label></td>
</tr>
<tr><td>
<label><input type="radio" name="_id0:sor" value="33"
border="1" title="Select any one of the choice">
Pepsi</input></label></td>
</tr>
<tr><td>
<label><input type="radio" name="_id0:sor" value="44"
border="1" title="Select any one of the choice">
Sprite</input></label></td>
</tr>
<tr><td>
<label><input type="radio" name="_id0:sor" value="55"
border="1" title="Select any one of the choice">
Frooti</input></label></td>
</tr>
<tr><td>
<label><input type="radio" name="_id0:sor" value="66"
border="1" title="Select any one of the choice"> Coca-
Cola</input></label></td>
</tr>
</table>
<input type="hidden" name="_id0" value="_id0" /></form>
</body>
</html>

All the attributes of this tag have been summarized below :


• id : It is the component identifier that must be unique in the closest container.
• layout : This attribute is used to set the components either vertically or horizontally by
two values "lineDirection" and "pageDirection" respectively.This attribute takes
"lineDirection" value bydefault.
• enabledClass : This attribute is used to set the CSS class to the label of disabled choices.
• disabledClass : This attribute is used to set the CSS class to the label of enabled choices.
• binding : It takes the value binding expression that is used to link the component to the
property of the backing bean.
• rendered : Its a boolean attribute. Its default value is true. It determines whether this
component should be rendered or not.
• value : This is to set the current value of the component.
• converter : This specifies the converter for the component. This can be static value or EL
expression .
• immediate : Its a boolean attribute. It is used to identify during which phase value
change event should occur. If this attribute is set to true then in place of firing the event
during the process validation phase, these event are sent immadiately at the end of apply
request values phase.
• required : Its a boolean attribute. It indicates that its value is required by the user before
the submission of the form to the server. If it is set to true and value is not provided then
an error message comes.
• validator : It takes the method binding expression. This expression represents the
validator method. This method is called at the time of validation of the component.
• valueChangeListener : This also takes a method binding expression. This expression
represents value change listener method. This method will be called when new value is
set for this component.
• border : It is used to set the border width of the table containing these choices.
• dir : It is used to set the direction of the text to be displayed. It can take two values
LTR(left to right) and RTL (right to left).
• lang : It is used to set the base language of the component when displayed.
• style : It is used to set the CSS style definition for the component.
• title : It is the standard html attribute.It is used to set the tooltip text for this component.
• styleClass : It is used to set the CSS class for the component.
• onclick : Script to be invoked when the element is clicked.
• ondblclick : It is used for Java Script code to be invoked when the element is double-
clicked.
• onmousedown : It is used for Java Script code to be invoked when the pointing device is
pressed over this element.
• onmouseup : It is used for Java Script code to be invoked when the pointing device is
released over this element.
• onmouseover : It is used for Java Script code to be invoked when the pointing device is
moved into this element.
• onmousemove : It is used for Java Script code to be invoked when the pointing device is
moved while it is in this element.
• onmouseout : It is used for Java Script code to be invoked when the pointing device is
moves out of this element.
• onkeypress : It is used for Java Script code to be invoked when a key is pressed over this
element.
• onkeydown : It is used for Java Script code to be invoked when a key is pressed down
over this element.
• onkeyup : It is used for Java Script code to be invoked when a key is released over this
element.
• accesskey : This is standard html attribute. It is used to set the access key for the element
which is used to send the focus to the element when pressed.
• alt : This is used as an alternate text that is displayed when browser is not able to display
the element.
• disabled : Its a boolean attribute. This is used to disable the element to receive focus,
when it is set to true.
• onblur : It is used to set the java script code to execute when focus is lost from the
element.
• onfocus : It is used to set the java script code to execute when focus is received by the
element.
• onchange : It is used to set the java script code to execute when element is modified.
• onselect : It is used to set the java script code to execute when element is modified
• readonly : Its a boolean attribute. It is used to indicate the user that its value can't be
modified, if it is set to true.
• tabindex : This is a standard html attribute. It is used to set the order of receiving the
focus on the movement of TAB key by the user.
JSF Core Tag Reference

This section is dedicated to make you understand about JSF Core Tags. All these core tags are
contained in JSF Core Tag Library. All of these tags are independent of any particular render
kit and perform core actions. To make us enable to use these tags we have to use "taglib"
directive at the top of code where "uri" is set to http://java.sun.com.jsf/core and "prefix" is
set to "f". Here f is used conventionally but you can use any value of this prefix attribute. uri
is used to specify where the core tag library is located. For example :
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"
%>
Now any core tag can be used with the help of prefix "f". For example :

1. <f:view locale="fr">
..............
..............
</f:view>
2. <f:loadBundle basename="RB" var="mes"/>

Here in the above ex. view and loadBundle tags have been used with the use of prefix "f" and
(attribute, value) pair can be used to provide different functionality. These attributes can be
(required) necessary to be mentioned or not depending on the tags used. For ex. in the view
tag lacale is not required to be mentioned. If we want to set the locale to "fr" then you can use
this attribute otherwise not required to use. But in the second case of loadBundle, both the
attributes "basename" and "var" are necessary to be mentioned. All these core tags and all
attributes will be discussed in detail in the following sections of this tutorial.
JSF actionListener Tag
This tag is used to add a action listener to the component associated with the enclosing tag.
When user does an event on the component then this action takes place. The class where this
action is defined implements ActionListener interface. In this example this class is
"MyBean.java" in roseindia package. Within this class a method processAction() is written,
where we write our logic of action.
Code Description :
<%@ page contentType="text/html" %>
<%@ taglib uri="http://java.sun.com/jsf/html"
prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core"
prefix="f" %>

<f:view>
<html>
<body>
<h:form id="form1">
<h:commandButton id="button1"
value="Click">
<f:actionListener
type="roseindia.MyBean" />
</h:commandButton>
</h:form>
</body>
</html>
</f:view>
MyBean.java :
package roseindia;

import java.util.*;
import javax.swing.*;
import javax.faces.event.*;

public class MyBean implements


ActionListener,ValueChangeListener{
String som = "";
private Date today = new Date();
public void processAction(ActionEvent e){
JOptionPane.showMessageDialog(null,"Hi");
}

public void processValueChange(ValueChangeEvent ce){


JOptionPane.showMessageDialog(null, ce.getSource());
}

public String getSom(){


return som;
}

public void setSom(String som){


this.som = som;
}

public Date getToday(){


return today;
}

public void setToday(Date today) {


this.today = today;
}
}
Rendered Output : This is the first page that appears to the user. There is one form button
which when clicked renders a message dialog as it is shown in the second picture below.
Html Source Code :
<html>
<body>
<form id="form1" method="post" action="/f-
tags/pages/actionListener/actionListener.jsf"
enctype="application/x-www-form-
urlencoded">
<input id="form1:button1" type="submit"
name="form1:button1" value="Click" />
<input type="hidden" name="form1"
value="form1" /></form>
</body>
</html>
This tag contains one attribute :
type : This attribute is used to specify the fully qualified name of the class which has
implemented ActionListener interface and implemented processAction() method.

JSF attributeTag

This tag is used to add attribute to the nearest parent component. This is name/value pair
where name takes the attribute name which will be set to the component and value takes the
value of the attribute. In this example, command button tag is assigned only one attribute "id",
then attribute tag is used to assign more attributes and its values. For example, instead of
specifying "value" attribute and its value "Click" ( i.e. value="Click") in commandButton
tag parallel to "id" attribute, this has been associated to the component using attribute tag.
Code Description :
<%@ page contentType="text/html" %>
<%@ taglib uri="http://java.sun.com/jsf/html"
prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core"
prefix="f" %>

<f:view>
<html>
<body>
<h:form id="form1">
<h:inputText value="Enter Name" />
<h:commandButton id="button1">
<f:attribute name="value"
value="Click"></f:attribute>
</h:commandButton>
</h:form>
</body>
</html>
</f:view>
Rendered Output :

Html Source Code :


<html>
<body>
<form id="form1" method="post" action="/f-
tags/pages/attribute/attribute.jsf"
enctype="application/x-www-form-
urlencoded">

<input type="text" name="form1:_id0"


value="Enter Name" />
<input id="form1:button1" type="submit"
name="form1:button1" value="" />
<input type="hidden" name="form1"
value="form1" /></form>
</body>
</html>
This tag contains two attributes :
name : This is the required attribute which is used to specify the name of the attribute of the
nearest parent component.
value : This is the required attribute which is used to specify the value of the attribute
specified in name attribute of this tag.
JSF convertDateTime Tag

This tag is useful converting date and time according to your format. It supports many
attributes which can give different styles of presenting date and time like locale attribute
formats the date and time according to locale and dateStyle, timeStyle determines how date
and time is to be formatted. Date and time can be formatted according to the time zone by
setting the timeZone attribute. We have made a simple program to illustrate this tag.
Code Description :
<%@ page contentType="text/html" %>
<%@ taglib uri="http://java.sun.com/jsf/html"
prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core"
prefix="f" %>

<f:view>
<html>
<body>
<h:form id="form1">
<h:outputText value="#{MyBean.today}">
<f:convertDateTime type="both"
dateStyle="short"/>
</h:outputText>
</h:form>
</body>
</html>
</f:view>
Rendered Output :
Html Source Code :
<html>
<body>
<form id="form1" method="post" action="/f-
tags/pages/convertDateTime/convertDateTime.jsf"
enctype="application/x-www-form-urlencoded">
5/14/07 12:55:42 PM
<input type="hidden" name="form1"
value="form1" /></form>
</body>
</html>
This tag contains some attributes:
dateStyle : This is used to set the style of date to be presented to the page. This attribute is
applied only if the type attribute is "date" or "both". This attribute can take some values like :
1. default May 14, 2007 2:35:45 PM ( Default Value)
2. short 5/14/07 12:55:42 PM
3. medium May 14, 2007 2:42:36 PM
4. long May 14, 2007 2:41:08 PM
5. full Monday, May 14, 2007 2:39:56 PM
timeStyle : This is used to set the style of time to be presented to the page. This attribute is
applied only if the type attribute is "time" or "both". It also can take values default ( Default
Value), short, medium, long, full.
locale : This is used to specify the name of the locale for which we have to format the date and
time.
pattern : This is used to set the formatting pattern as defined in java.text.SimpleDateFormat.
This is used to determine how the date and time will be formatted.
timeZone : This attribute is used to set the time zone for which the date and time is to be
formatted. Its default time zone is GMT time zone.
type : It is used to specify whether date, time or both is to be formatted. Its valid values are
"date" (dafault), "time" and "both".
JSF converter Tag

This tag is used to register the converter instance on the enclosing component. Many times it
is required to convert the input to the appropriate type. In this case this tag can be useful. It
takes one required attribute "converterId". In this attribute we specify the name of backing
bean class which implements Converter interface. You have to maintain the faces-config file
where converter-id and converter-class is specified within the converter element.
Code Description :
<%@ page contentType="text/html" %>
<%@ taglib uri="http://java.sun.com/jsf/html"
prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core"
prefix="f" %>

<f:view>
<html>
<body>
<h:form id="form1">
<table>
<tr>
<td><font color="#FF0000"><h:message
for="name" /></font></td>
<td>&nbsp;</td>
</tr>
<tr>
<td>
<h:inputText id="name">
<f:converter converterId="javax.faces.Short"/>
</h:inputText>
</td>
<td><h:commandButton value="Submit"
/></td>
</tr>
</table>
</h:form>
</body>
</html>
</f:view>
Rendered Output : This is the first output that comes in front of the user.
When user inputs wrong input that can not be converted to the appropriate type then the
conversion error occurs, like below :

Html Source Code :


<html>
<body>
<form id="form1" method="post" action="/f-
tags/pages/converter/converter.jsf"
enctype="application/x-www-form-urlencoded">
<table>
<tr><td><font color="#FF0000"></font></td>
<td>&nbsp;</td>
</tr><tr><td>
<input id="form1:name" type="text"
name="form1:name" />
</td>
<td><input type="submit" name="form1:_id1"
value="Submit" /></td>
</tr>
</table>
<input type="hidden" name="form1"
value="form1" /></form>
</body>
</html>
This tag contains one attribute :

converterId : This is the required attribute and is used to specify the ID of the converter class
which is used in the conversion process (in the case of custom conversion).
JSF convertNumber Tag

This tag is used to register the NumberConverter instance on the enclosing component. This
class is responsible to convert String to java.util.Number object and vice-versa.
Code Description :
<%@ page contentType="text/html" %>
<%@ taglib uri="http://java.sun.com/jsf/html"
prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core"
prefix="f" %>

<f:view>
<html>
<body>
<h:form id="form1">
<table>
<tr>
<td><font color="#FF0000"><h:message
for="number" /></font></td>
<td>&nbsp;</td>
</tr>
<tr>
<td>
<h:inputText id="number">
<f:convertNumber currencySymbol="$"
type="currency"
groupingUsed="#{false}"></f:convertNumber>
</h:inputText>
</td>
<td><h:commandButton value="Submit"
/></td>
</tr>
</table>
</h:form>
</body>
</html>
</f:view>
Rendered Output : This is the first output that comes in front of the user.

When user inputs wrong input that does not start with the $ sign then error occurs, like below :

Html Source Code :


<html>
<body>
<form id="form1" method="post" action="/f-
tags/pages/convertNumber/convertNumber.jsf"
enctype="application/x-www-form-urlencoded">

<table>
<tr><td><font color="#FF0000"></font></td>
<td>&nbsp;</td>
</tr><tr><td>
<input id="form1:number" type="text"
name="form1:number" />
</td>
<td><input type="submit" name="form1:_id1"
value="Submit" /></td>
</tr>
</table>

<input type="hidden" name="form1"


value="form1" /></form>
</body>
</html>
This tag contains some attributes:

currencyCode : In this attribute ISO 4217 currency code is set that will be applied when
converting currency values.
currencySymbol : This sets the currency symbol that will be applied when formatting
currency values.
groupingUsed : This is the boolean attribute and is used to specify whether the output will
contain grouping seperators. Its default value is "true".
integerOnly : This is the boolean attribute and is used to specify whether only the integer part
will be parsed.Its default value is "false".
locale : This is used to specify the name of the locale for which we have to format the number.
maxFractionDigits : It is used to specify the maximum no. of digits in the fractional part that
will be formated.
maxIntegerDigits : It is used to specify the maximum no. of digits in the integer part that will
be formated.
minFractionDigits : It is used to specify the minimum no. of digits in the fractional part that
will be formated.
minIntegerDigits : It is used to specify the minimum no. of digits in the integer part that will
be formated.
pattern : This is used to set the formatting pattern.
type : It is used to specify the type of formatting. Its valid values are "number" "currency"
"percentage". Its default value is "number".
JSF facet Tag

This tag is used to add a facet to the component means this tag is used to add its child as a
facet of the closest parent component. With the help of this tag we can add header and footer
facet to the container component like panelGroup.
Code Description :
<%@ taglib uri="http://java.sun.com/jsf/html"
prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core"
prefix="f"%>

<f:view>
<html>
<body>
<h:form>
<h:panelGrid columns="2" border="1" rules="rows"
title="This is facet tag demo">
<f:facet name="header">
<h:outputText value="header facet"/>
</f:facet>
<h:outputText value="First Name"/>
<h:inputText/>
<h:outputText value="Last Name"/>
<h:inputText/>
<h:outputText value="Address"/>
<h:inputText/>
<h:commandButton value="submit"/>

<f:facet name="footer">
<h:outputText value="footer facet" />
</f:facet>
</h:panelGrid>
</h:form>
</body>
</html>
</f:view>
Rendered Output :

Html Source Code :


<html>
<body>
<form id="_id0" method="post"
action="/coretag/pages/facet.jsf"
enctype="application/x-www-form-urlencoded">
<table border="1" rules="rows" title="This is facet
tag demo">
<thead>
<tr><th colspan="2" scope="colgroup">header
facet</th></tr>
</thead>

<tfoot>
<tr><td colspan="2">footer facet</td></tr>
</tfoot>
<tbody>
<tr>
<td>First Name</td>
<td><input type="text" name="_id0:_id4" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="_id0:_id6" /></td>
</tr>
<tr>
<td>Address</td>

<td><input type="text" name="_id0:_id8" /></td>


</tr>
<tr>
<td><input type="submit" name="_id0:_id9"
value="submit" /></td>
</tr>
</tbody>
</table>

<input type="hidden" name="_id0" value="_id0"


/></form>
</body>
</html>
This tag contains one attribute :

name : This is the required attribute and is used to set the name of the facet. "header" and
"footer" values can be used for this attribute.
JSF loadBundle Tag

This tag is used to load the recourse bundle and store it as a map in the request scope. This
allows you to access the message in your JSF. There are two attributes for this tag "basename"
and "var". "basename" is the base name where the bundle is present and "var" represents the
name by which the we will refer this bundle in our jsf page.
Code Description :
<%@ taglib uri="http://java.sun.com/jsf/html"
prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core"
prefix="f"%>
<f:loadBundle basename="RB" var="mes"/>
<f:view>
<html>
<body>
<h:form>
<h:outputText
value="#{mes.greeting_text}" />
</h:form>
</body>
</html>
</f:view>
Resource Bundle file(RB.properties in WEB_INF/classes folder):
greeting_text=Welcome In Roseindia JSF Tutorial
Rendered Output :

Html Source Code :


<html>
<body>
<form id="_id0" method="post"
action="/coretag/pages/resourceBundle.jsf"
enctype="application/x-www-form-urlencoded">

Welcome In Roseindia JSF Tutorial

<input type="hidden" name="_id0" value="_id0"


/></form>

</body>
</html>
Attributes that this tag uses are given below :

basename : It is used to provide the name of the base of the resource bundle which is to be
loaded and used in our pages.
var :This is used to give the name of the attribute in request scope, where the bundle is stored
as a map, to access the bundle by this name.
JSF param Tag

This tag is used to set the parameter to the enclosing component. This tag is helpful in the case
of creating the compound message. Its value attribute can be set using EL to get the current
value from the backing bean property. Suppose you are using outputFormat tag to create
compound message where these param values can be used.
Code Description : In the code below {0}and {1}are replaced by the param values specified
within outputFormat tag. param values are being taken from properties of backing bean
"MessageBean".
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<f:view>
<html>
<body>
<h:form>
<h:outputFormat value="Hi,{0}. This is to inform you,{1} is
your password .">
<f:param value="#{MessageBean.a}" />
<f:param value="#{MessageBean.b}" />
</h:outputFormat>
</h:form>
</body>
</html>
</f:view>
Output Rendered :
Html Source Code :
<html>
<body>
<form id="_id0" method="post"
action="/coretag/pages/param.jsf" enctype="application/x-www-
form-urlencoded">
Hi,Alex. This is to inform you,123456 is your password .
<input type="hidden" name="_id0" value="_id0" /></form>
</body>
</html>
This tag contains some attributes that are explained below :
binding : This attribute takes value binding expression to link component to the banking bean
property.
id : This is used to uniquely identify the component.
name : This is used to set the name of the parameter.
value : This is used to set the value of the parameter.
JSF selectItem Tag

This tag is used to add a child component to the component associated with the enclosing tag.
In this section you will learn about the selectItem tag. It can be used with any select tag of JSF
html tag library. It renders "option" element when converted to html. In the example below
selectItem tag has been used within selectManyListbox tag. So these are the child components
of List Box component and these child components provides options for the List Box
component.
Code Description :
<%@ taglib uri="http://java.sun.com/jsf/html"
prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core"
prefix="f"%>

<f:view>
<html>
<body>
<h:form>
<h:outputText value="Select windows to
open"/><br><br>
<h:selectManyListbox id="subscriptions"
value="#{TableBean.perInfoAll}" size="3">
<f:selectItem id="si1" itemLabel="window1"
itemValue="w1" />
<f:selectItem id="si2" itemLabel="window2"
itemValue="w2" />
<f:selectItem id="si3" itemLabel="window3"
itemValue="w3" />
<f:selectItem id="si4" itemLabel="window4"
itemValue="w4" />
<f:selectItem id="si5" itemLabel="window5"
itemValue="w5" />
<f:selectItem id="si6" itemLabel="window6"
itemValue="w6" />
</h:selectManyListbox>
</h:form>
</body>
</html>
</f:view>
Rendered Output :

Html Source Code :


<html>
<body>
<form id="_id0" method="post"
action="/coretag/pages/selectItem.jsf"
enctype="application/x-www-form-urlencoded">

Select windows to open<br><br>


<select id="_id0:subscriptions"
name="_id0:subscriptions" multiple size="3">

<option value="w1">window1</option>
<option value="w2">window2</option>
<option value="w3">window3</option>
<option value="w4">window4</option>
<option value="w5">window5</option>
<option value="w6">window6</option>
</select>
<input type="hidden" name="_id0" value="_id0"
/></form>

</body>
</html>
This tag contains some attributes :
id : This is used to uniquely identify the table component. This must be unique within the
closest parent component.
binding : It is a value binding expression that is used to link component to a property in a
backing bean.
itemLabel : This is used to set the label for the option rendered by this tag.
itemValue : This is used to set the value for the option rendered by this tag. This value is used
at server when option is selected.
value : This is the value binding expression that indicates to the selectItem instance which
contains the information about the option.
itemDescription : It is used to describe something about this option for your own purpose.
itemDisabled : This is a boolean attribute and is used to make the option enable or disable
when it is set to "true" and "false" respectively. Its default value is "false".
This tag is used to add a child component to the component associated with the enclosing tag.
In this section you will learn about the selectItem tag. It can be used with any select tag of JSF
html tag library. It renders "option" element when converted to html. In the example below
selectItem tag has been used within selectManyListbox tag. So these are the child components
of List Box component and these child components provides options for the List Box
component.
Code Description :
<%@ taglib uri="http://java.sun.com/jsf/html"
prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core"
prefix="f"%>

<f:view>
<html>
<body>
<h:form>
<h:outputText value="Select windows to
open"/><br><br>
<h:selectManyListbox id="subscriptions"
value="#{TableBean.perInfoAll}" size="3">
<f:selectItem id="si1" itemLabel="window1"
itemValue="w1" />
<f:selectItem id="si2" itemLabel="window2"
itemValue="w2" />
<f:selectItem id="si3" itemLabel="window3"
itemValue="w3" />
<f:selectItem id="si4" itemLabel="window4"
itemValue="w4" />
<f:selectItem id="si5" itemLabel="window5"
itemValue="w5" />
<f:selectItem id="si6" itemLabel="window6"
itemValue="w6" />
</h:selectManyListbox>
</h:form>
</body>
</html>
</f:view>
Rendered Output :

Html Source Code :


<html>
<body>
<form id="_id0" method="post"
action="/coretag/pages/selectItem.jsf"
enctype="application/x-www-form-urlencoded">
Select windows to open<br><br>
<select id="_id0:subscriptions"
name="_id0:subscriptions" multiple size="3">

<option value="w1">window1</option>
<option value="w2">window2</option>
<option value="w3">window3</option>
<option value="w4">window4</option>
<option value="w5">window5</option>
<option value="w6">window6</option>
</select>
<input type="hidden" name="_id0" value="_id0"
/></form>

</body>
</html>
This tag contains some attributes :
id : This is used to uniquely identify the table component. This must be unique within the
closest parent component.
binding : It is a value binding expression that is used to link component to a property in a
backing bean.
itemLabel : This is used to set the label for the option rendered by this tag.
itemValue : This is used to set the value for the option rendered by this tag. This value is used
at server when option is selected.
value : This is the value binding expression that indicates to the selectItem instance which
contains the information about the option.
itemDescription : It is used to describe something about this option for your own purpose.
itemDisabled : This is a boolean attribute and is used to make the option enable or disable
when it is set to "true" and "false" respectively. Its default value is "false".
JSF selectItems Tag

This tag is used to add a set of items to the nearest enclosing parent (select one or select many)
component. This tag can be used to get the list of choices from the list of objects from backing
bean. So instead of writing many selectItem tag for choices, you can use selectItems tag to
get the options list in the form of list of objects from backing bean.
Code Description :
<%@ taglib uri="http://java.sun.com/jsf/html"
prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core"
prefix="f"%>

<f:view>
<html>
<body>
<h:form>
<h:outputText value="Select choices given
below :"/><br><br>
<h:selectManyListbox id="subscriptions"
value="#{SItemsBean.options}" size="3">
<f:selectItems value="#{SItemsBean.options}" />
</h:selectManyListbox>
</h:form>
</body>
</html>
</f:view>
Backing Bean (SItemsBean.java) : In the code below, we have taken array list of SelectItem
objects. It has 5 constructors. One of its constructor accepts value as Object and label as String
parameter while the another one accepts value as Object, label as String, description as String
disabled as boolean parameters. description parameter is used for own purpose to describe
something and disabled is used to make the option enabled or disabled by setting it "true" and
"false" respectively. You can use them according to the need. You can understand it better by
the code given below :
import javax.faces.model.SelectItem;
import java.util.*;

public class SItemsBean


{
private List options;
public SItemsBean()
{
options = new ArrayList();
SelectItem option = new SelectItem("ch1", "choice1", "This bean is for
selectItems tag", true);
options.add(option);
option = new SelectItem("ch2", "choice2");
options.add(option);
option = new SelectItem("ch3", "choice3");
options.add(option);
option = new SelectItem("ch4", "choice4");
options.add(option);
option = new SelectItem("ch5", "choice5);
options.add(option);
}

public void setOptions(List opt)


{
options = opt;
}

public List getOptions()


{
return options;
}
}
Rendered Output :

Html Source Code :


<html>
<body>
<form id="_id0" method="post"
action="/coretag/pages/selectItems.jsf"
enctype="application/x-www-form-urlencoded">
Select choices given below :<br><br>
<select id="_id0:subscriptions"
name="_id0:subscriptions" multiple size="3">
<option value="ch1"
disabled="disabled">choice1</option>
<option value="ch2">choice2</option>
<option value="ch3">choice3</option>
<option value="ch4">choice4</option>
<option value="ch5">choice5</option>
</select>
<input type="hidden" name="_id0" value="_id0"
/></form>
</body>
</html>
This tag contains some attributes :
id : This is used to uniquely identify the table component. This must be unique within the
closest parent component.
binding : It is a value binding expression that is used to link component to a property in a
backing bean.
value : This is the value binding expression that indicates to the list or array of selectItem
instances which contains the information about the option.
JSF subview Tag

This tag is used to create the sub-view of the view. It contains all JSF tags in a page that is
included in another JSP page. It acts as a naming container so that the components inside it
can be made unique. This naming container contains JSF tags on a nested page by
<jsp:include> or the tag which includes the page dynamically. To include another JSP or JSF
page, using <jsp:include> or <c:import>, we must use <f:subview> tag around it so that JSF
process the included file properly. subview.jsp is the main page where subview tag is used to
include next.jsp page.
Code Description :

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

<f:view locale="fr">
<html>
<head>
<link href="corestyle.css" rel="stylesheet"
type="text/css"/>
</head>
<body>
<h:form>
<h:outputText value="Enter your name
below"/><br><br>
<h:inputText id="ab" value="#{MessageBean.b}"
required="true"/>
<h:message for="ab"
errorClass="errors"/><br><br>
<h:commandButton value="go"/><br><br><br>

<f:subview id="next">
<jsp:include page="next.jsp" />
</f:subview>

</h:form>
</body>
</html>
</f:view>
next.jsp :
<hr>
<b> RoseIndia JSF tutorial</b>
<hr>
Rendered Output :
Html Source Code :
<html>
<head>
<link href="corestyle.css" rel="stylesheet"
type="text/css"/>
</head>
<body>
<form id="_id0" method="post"
action="/coretag/pages/subview.jsf"
enctype="application/x-www-form-urlencoded">
Enter your name below<br><br>
<input id="_id0:ab" type="text"
name="_id0:ab" />
<br><br>
<input type="submit" name="_id0:_id3"
value="go" /><br><br><br>
<hr><b> RoseIndia JSF tutorial</b><hr>
<input type="hidden" name="_id0"
value="_id0" /></form>
</body>
</html>
Attributes that this tag uses are given below :

id : This is used to uniquely identify this component within the scope of enclosing naming
container.
binding : It takes value binding expression to bind this component to the backing bean
property.
rendered : It takes the boolean value (default value is "true") that is used to specify whether
this component should be rendered or not.
JSF validateDoubleRange Tag

This is one of the standard validators provided by JSF to check whether the floating point
value (or that can be converted to floating point) entered in the corresponding input
component is within the certain range. This range is specified by minimum and maximum
attributes of this tag.The page author requires no code to write for validation. Simply use this
tag in the nearest enclosing input component. If there is any fault in filling the input
component then the error message flashes to show this error.
Code Description :
<%@ taglib uri="http://java.sun.com/jsf/html"
prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core"
prefix="f"%>

<f:view>
<html>
<body>
<h:form>
<h:outputText value="Enter any floating point
value"/>
<br><br>
<h:inputText id="no" value="#{MessageBean.a}"
required="true">
<f:validateDoubleRange minimum="2.0"
maximum="10.0"/>
</h:inputText>
<h:message for="no"/>
</h:form>
</body>
</html>
</f:view>
Rendered Output :
This is the first screen that will be rendered to the user.
When the user enters the value out of the range from 2.0 to 10.0 then validation error is
displayed specifying that the user has not entered the correct value or type. Figure below
shows this fact :

Html Source Code :


<html>
<body>
<form id="_id0" method="post"
action="/coretag/pages/validateDoubleRange.jsf"
enctype="application/x-www-form-urlencoded">
Enter any floating point value
<br><br>
<input id="_id0:no" type="text" name="_id0:no" />
<input type="hidden" name="_id0" value="_id0"
/></form>
</body>
</html>
This tag contains two attributes :
maximum : This attribute is used to set the maximum value allowed for this component to
input
minimum : This is used to set the minimum value allowed to be entered in the component.
JSF validateLength Tag

If you want the user to input the number of characters between the certain range, suppose you
want the user to fill password of more than 6 characters then this tag can be used to validate.
This is one of the standard validators provided by JSF to check whether the length of the local
value entered in the corresponding input component is within the certain range. This range is
specified by minimum and maximum attributes of this tag. The page author requires no code
to write for validation. Simply use this tag in the nearest enclosing input component. If there is
any fault in filling the input component then the error message flashes to show this error. In
the following example, the user has entered less than 6 characters in the password field so
error message displaying that user has entered less than 6 characters in the password field.
Code Description :
<%@ taglib uri="http://java.sun.com/jsf/html"
prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core"
prefix="f"%>

<f:view>
<html>
<body>
<h:form><h:outputText value="ID"/><br>
<h:inputText id="ID" value="#{MessageBean.a}"
required="true"/>
<h:message for="ID"/>
<br><br>
<h:outputText value="PASSWORD(minimum 6
characters)"/><br>
<h:inputSecret id="PWD" value="#{MessageBean.b}"
required="true" >
<f:validateLength maximum="15" minimum="6"/>
</h:inputSecret>
<h:message for="PWD"/>
<br><br>
<h:commandButton value="submit" />
</h:form>
</body>
</html>
</f:view>
Rendered Output :
This is the first screen that will be rendered to the user.
When the user enters the value less than 6 characters or more than 15 characters then
validation error is displayed specifying that the user has not entered the correct value. Figure
below shows this fact :

Html Source Code :


<html>
<body>
<form id="_id0" method="post"
action="/coretag/pages/validateLength.jsf"
enctype="application/x-www-form-urlencoded">
ID<br>
<input id="_id0:ID" type="text" name="_id0:ID"
value="" />

<br><br>
PASSWORD(minimum 6 characters)<br>

<input id="_id0:PWD" type="password"


name="_id0:PWD" value="" />

<br><br>
<input type="submit" name="_id0:_id5"
value="submit" />
<input type="hidden" name="_id0" value="_id0"
/></form>
</body>
</html>
This tag contains two attributes :
maximum : This attribute is used to set the maximum length allowed for this component to
input
minimum : This is used to set the minimum length allowed to be entered in the component.
JSF validateLongRange Tag

This is one of the standard validators provided by JSF to check whether the local value (a
numeric value or any string that can be converted to a long.) entered in the corresponding
input component is within the certain range. This range is specified by minimum and
maximum attributes of this tag. The page author requires no code to write for validation.
Simply use this tag in the nearest enclosing input component. If there is any fault in filling the
input component then the error message flashes to show this error.
Code Description :
<%@ taglib uri="http://java.sun.com/jsf/html"
prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core"
prefix="f"%>

<f:view>
<html>
<body>
<h:form>
<h:inputText id="it" value="#{MessageBean.a}">
<f:validateLongRange maximum="30"
minimum="15"/>
</h:inputText>
<h:message for="it"/><br><br>
<h:commandButton value="submit" />
</h:form>
</body>
</html>
</f:view>
Rendered Output :
This is the first screen that will be rendered to the user.

When the user enters the value out of the range from 15 to 30 then validation error is displayed
specifying that the user has not entered the correct value. Figure below shows this fact :

Html Source Code :


<html>
<body>
<form id="_id0" method="post"
action="/coretag/pages/validateLongRange.jsf"
enctype="application/x-www-form-urlencoded">
<input id="_id0:it" type="text" name="_id0:it"
value="" />
<br><br>
<input type="submit" name="_id0:_id2"
value="submit" />

<input type="hidden" name="_id0" value="_id0"


/></form>
</body>
</html>
This tag contains two attributes :
maximum : This attribute is used to set the maximum value allowed for this component to
input
minimum : This is used to set the minimum value allowed to be entered in the component.
JSF validator Tag

This tag is used to add and register the validator to the nearest parent component. Typically all
applications requires filling some or more information in the page. So it will be better
approach to find out the invalid information value or format as soon as possible to make it user
friendly. So user can find out faults and correct it. JSF provides built-in validation rules. JSF
also helps to customize the validation rules to make it according to the need. If the component
has input value then the conversion of the value to the required type is needed and then
specified validator type is invoked to check whether this value is of required format and type.
This tag contains one attribute named "validatorID" which is required attribute. In this
attribute we specify the name of backing bean class where we write functionality according to
our need.For custom validation Validator interface is implemented in the class providing
validation. You have to maintain the faces-config file where validator-id and validator-class
is specified within the validator element. Here, one thing that we have to take care is that
validator-id in both places (in faces-config file and validator tag in jsp file ) should match.
Code Description :
<%@ page contentType="text/html" %>
<%@ taglib uri="http://java.sun.com/jsf/html"
prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core"
prefix="f" %>

<f:view>
<html>
<body>
<h:form id="form1">
<table>
<tr>
<td><font color="#FF0000"><h:message
for="email" /></font></td>
<td>&nbsp;</td>
</tr>
<tr>
<td>
<h:inputText id="email" required="true">
<f:validator validatorId="checkvalidemail" />
</h:inputText>
</td>
<td><h:commandButton value="Submit"
/></td>
</tr>
</table>
</h:form>
</body>
</html>
</f:view>
Backing Bean (Validation.java) : The code below is for backing bean used in this example.
package roseindia;

import javax.faces.*;
import javax.faces.validator.*;
import javax.faces.application.*;
import javax.faces.component.*;
import javax.faces.context.*;
import java.util.regex.*;
public class validation implements Validator{
public validation(){}

public void validate(FacesContext facesContext, UIComponent


uIComponent, Object object) throws ValidatorException{
String enteredEmail = (String)object;
Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
Matcher m = p.matcher(enteredEmail);
boolean matchFound = m.matches();

if (!matchFound) {
FacesMessage message = new FacesMessage();
message.setSummary("Invalid Email ID.");
throw new ValidatorException(message);
}
}
}
Now we have to register this class in the faces-config file like below :
<faces-config>
..................
..................
<validator>
<validator-
id>checkvalidemail</validator
-id>
<validator-
class>roseindia.validation</val
idator-class>
</validator>
.................
.................
</faces-config>
Here in this above case "checkvalidemail" specified in "validator-id" is the alias name (this
will be used in jsp file to access the actual backing bean class) of the actual class specified in
"validator-class" in the faces-config file. For ex.
Rendered Output :

If we enter incorrect email address then its validation process makes it invalid and shows error
message to the user, like below.

Html Source Code :


<html>
<body>
<form id="form1" method="post" action="/f-
tags/pages/validator/validator.jsf"
enctype="application/x-www-form-urlencoded">
<table>
<tr>
<td><font color="#FF0000"></font></td>
<td>&nbsp;</td>
</tr><tr><td>
<input id="form1:email" type="text"
name="form1:email" />
</td>
<td><input type="submit" name="form1:_id1"
value="Submit" /></td>
</tr>
</table>

<input type="hidden" name="form1"


value="form1" /></form>
</body>
</html>
This tag contains one attribute :

validatorId : This is the required attribute and is used to specify the ID of the validator class
which we are going to use in this validation process (in the case of custom validation). This
value must match with the validator-id element specified in validator tag of faces-config file.
JSF valueChangeListener Tag

This tag is used to add a value change listener to the component associated with the enclosing
tag. Value change event is fired when the user changes the input value. This event can be fired
with any component which takes user input (select or input components). The class which is
registered with the component implements ValueChangeListener interface and implements the
method processValueChange(). We write our logic of action in this method. One thing that
we have to take care is that we have to use onChange event of java script which submits the
form when input is changed. If we will not do this then we will have to submit the form
manually. This illustration will explain you how to go ahead.
Code Description :
<%@ page contentType="text/html" %>
<%@ taglib uri="http://java.sun.com/jsf/html"
prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core"
prefix="f" %>

<f:view>
<html>
<body>
<h:form>
<h:selectOneMenu id="som"
value="#{MyBean.som}" title="select any
one in this menu" onchange="submit()">
<f:selectItem id="si1" itemLabel="Thums
Up" itemValue="11" />
<f:selectItem id="si2" itemLabel="Limca"
itemValue="22" />
<f:selectItem id="si3" itemLabel="Pepsi"
itemValue="33" />
<f:selectItem id="si4" itemLabel="Sprite"
itemValue="44" />
<f:selectItem id="si5" itemLabel="Frooti"
itemValue="55" />
<f:selectItem id="si6" itemLabel="Coca-
Cola" itemValue="66" />
<f:valueChangeListener
type="roseindia.MyBean" />
</h:selectOneMenu>
</h:form>
</body>
</html>
</f:view>
MyBean.java :
package roseindia;

import java.util.*;
import javax.swing.*;
import javax.faces.event.*;

public class MyBean implements


ActionListener,ValueChangeListener{
String som = "";
private Date today = new Date();
public void processAction(ActionEvent e){
JOptionPane.showMessageDialog(null,"Hi");
}

public void processValueChange(ValueChangeEvent ce){


JOptionPane.showMessageDialog(null, ce.getSource());
}

public String getSom(){


return som;
}

public void setSom(String som){


this.som = som;
}

public Date getToday(){


return today;
}

public void setToday(Date today) {


this.today = today;
}
}
Rendered Output : This is the first page that appears to the user.

When the user changes the current value in the menu then the value change listener is
activated and gives its output according to the method processValueChange(). Here, in this
example, a message dialog is open and message is shown.
Html Source Code :
<html>
<body>
<form id="_id0" method="post" action="/f-
tags/pages/valueChangeListener/valueChangeL
istener.jsf" enctype="application/x-www-form-
urlencoded">
<select id="_id0:som" name="_id0:som"
size="1" onchange="submit()" title="select any
one in this menu">
<option value="11">Thums Up</option>
<option value="22">Limca</option>
<option value="33">Pepsi</option>
<option value="44">Sprite</option>
<option value="55">Frooti</option>
<option value="66">Coca-Cola</option>
</select>
<input type="hidden" name="_id0"
value="_id0" /></form>
</body>
</html>
This tag contains one attribute :
type : This attribute is used to specify the fully qualified name of the class which has
implemented valueChangeListener interface and implemented processValueChange()
method.
JSF verbatim Tag

This tag renders output component (UIOutput) within the closest component. It takes the
content from the body of this tag. This tag can be used to nest plain html within the JSF
component tree. Any Html and jsp tags in the view tag can be nested within verbatim tag. The
reason behind it is that all the content inside the f:view tag should be in the JSF component
tree. When JSF component tree is rendered, it contains only JSF components. But html and
JSP tags are not JSF components. So we nest the non JSF tags to the verbatim tag that treats
them as JSF components.
Code Description :
<%@ taglib uri="http://java.sun.com/jsf/html"
prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core"
prefix="f"%>

<f:view>
<html>
<body>
<h:form>
<f:verbatim>
<p><h3>This is the testing of verbatim tag of
jsf.</p></h3>
</f:verbatim>
</h:form>
</body>
</html>
</f:view>
Rendered Output :

Html Source Code :


<html>
<body>
<form id="_id0" method="post"
action="/coretag/pages/verbatim.jsf"
enctype="application/x-www-form-urlencoded">

<p><h3>This is the testing of verbatim tag of


jsf.</p></h3>
<input type="hidden" name="_id0" value="_id0"
/></form>
</body>
</html>
This tag contains attribute :
escape : Its a boolean attribute. Itss default value is "false". If it is made true then the
generated markup is escaped.
JSF view Tag

This tag is used to create the top level view. This acts as a container of all the components that
are part of the view of the page. Its attribute "locale" is important in the case of making the
view internationalized. We can do so by setting the locale attribute to the locale you have to
present the view of the page. Suppose we set the locale attribute to "en" or "fr" then the view
is presented to the user in English and French respectively. you can also set the locale
dynamically and can present the view according to the user.
Code Description :
<%@ taglib uri="http://java.sun.com/jsf/html"
prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core"
prefix="f"%>

<f:view locale="fr">
<html>
<head>
<link href="corestyle.css" rel="stylesheet"
type="text/css"/>
</head>
<body>
<h:form>
<h:inputText id="ab"
value="#{MessageBean.b}" required="true"/>
<h:message for="ab"
errorClass="errors"/><br>
<h:commandButton value="go"/>
</h:form>
</body>
</html>
</f:view>
Rendered Output : In the above code all component tags have been embedded in the view
tag.

In the above tag we have set the locale attribute to "fr" i.e. French locale. In the above code we
have used message tag to display the error message if the input field is left blank. So this
message is shown in French because of the locale set in the code. The output is shown below.
Html Source Code :
<html>
<head>
<link href="corestyle.css" rel="stylesheet"
type="text/css"/>
</head>
<body>
<form id="_id0" method="post"
action="/coretag/pages/view.jsf"
enctype="application/x-www-form-urlencoded">
<input id="_id0:ab" type="text"
name="_id0:ab" value="" /><br>
<input type="submit" name="_id0:_id2"
value="go" />
<input type="hidden" name="_id0"
value="_id0" /></form>
</body>
</html>
Attributes that this tag uses are given below :
locale : This attribute is used to set the locale of the view. Its default value is that specified in
configuration file. It can take static values or EL expressions.
Facelet component Tag

This tag is used to add a new component into the JSF component tree as children of UI
component instance. This tag shows its behavior like composition tag. The difference is that
the component tag inserts a new UIcomponent instance in the component tree and this instance
is the root of all its child components or fragments. The content outside of the tag is ignored as
it happens with composition tag.
Code Description :

comptemplate.xhtml :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets">
<head>
<title>facelet example </title>
</head>
<body>
Content above component tag will not be rendered.
<ui:component >
<h2>This is the content to be included in the page.</h2>
</ui:component >
Content below component tag will not be rendered.
</body>
</html>
Rendered Output :

Html Source Code :


<h2>This is the content to be included in the page.</h2>
This tag contains two attributes :
id : This attribute assigns unique identity to the component. Its not a required attribute. So if
you don't give id then facelet provides it automatically.
binding : This attribute is used to bind the component to the backing bean property.
Facelet composition Tag

This is a templating tag and is used for the wrapping the content that can be included in any
other facelet. This tag provides some useful features. Any content outside of this tag is left to
be rendered. You can include normal html content in your page but Facelet will render only
content that is within this tag i.e. composition tag. This tag takes one attribute named
"template". This attribute is set to the path of the template where the content of this tag will
be included.
Code Description :

composition.xhtml : In the code below we have taken template attribute which indicates the
template to which the content inside this composition tag will be rendered. Here we have
written some content outside of the composition tag, that content will not be rendered. In the
comptemplate.xhtml we have used insert tag to include the content inside the composition tag
to the comptemplate.xhtml page.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets">
<body>
Content above composition tag will not be rendered.
<ui:composition template="/pages/composition/comptemplate.xhtml">
<h2>This is the content to be included in the comptemplate.xhtml
page.</h2>
</ui:composition>
Content below composition tag will not be rendered.
</body>
</html>
comptemplate.xhtml :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets">
<head>
<title>facelet example </title>
<link href="../../style/CSS.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<ui:insert />
</body>
</html>
Rendered Output :
Html Source Code :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>facelet example </title>
<link href="../../style/CSS.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h2>This is the content to be included in the comptemplate.xhtml
page.</h2>
</body>
</html>
This tag contains only one attribute :
template : This attribute is set to the template where the content inside this tag will be
included.
Facelet debug Tag

This tag is useful in displaying the component tree and scoped variables. This information will
be displayed in a popup window of browser when we press Ctrl+Shift+(a key). This key will
be specified in hotkey attribute. For example, in the code below in "debugtemplate.xhtml",
this has been specified "p". So when page comes to the user then if Ctrl+Shift+p is pressed,
debug window is open which displays the component tree and scoped variables.

debug.xhtml :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<body>
Content above composition tag will not be rendered.
<ui:composition template="/pages/debug/debugtemplate.xhtml">
<ui:define name="face1">
<center><h2>RoseIndia Facelet Tags Tutorial</h2></center>
<h3>Welcome to the Facelet world..........</h3>
</ui:define>
<ui:define name="face2">Enter UserID :<br/>
<h:inputText id="it" /><br/><br/>
</ui:define>
<ui:define name="face3">Enter Password :<br/>
<h:inputSecret id="is" /><br/><br/>
</ui:define>
<ui:define name="face4">
<h:commandButton id="cb" value="Submit" />
</ui:define>
</ui:composition>
Content below composition tag will not be rendered.
</body>
</html>
debugtemplate.xhtml :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets">
<head>
<title>facelet example </title>
<link href="../../style/CSS.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<ui:insert name="face1"> </ui:insert>
<ui:insert name="face2"> </ui:insert>
<ui:insert name="face3"> </ui:insert>
<ui:insert name="face4"> </ui:insert>
<ui:debug hotkey="p" rendered="true"/>
</body>
</html>
Rendered Output : This is the page that is displayed to the user first. Now if we press
Ctrl+Shift+p then debug window is opened that is shown in the second figure below :
debug window :

Html Source Code :


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>facelet example </title>
<link href="../../style/CSS.css" rel="stylesheet" type="text/css" />
</head>
<body>
<center><h2>RoseIndia Facelet Tags Tutorial</h2></center>
<h3>Welcome to the Facelet world..........</h3>
Enter UserID :<br /><input id="it" type="text" name="it" /><br
/><br />
Enter Password :<br /><input id="is" type="password"
name="is" value="" /><br /><br />
<input id="cb" type="submit" name="cb" value="Submit" />
<script language="javascript" type="text/javascript">

//<![CDATA[
function faceletsDebug(URL) { day = new Date(); id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "',
'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,wi
dth=800,height=600,left = 240,top = 212');"); };var faceletsOrigKeyup =
document.onkeyup; document.onkeyup = function(e) { if (window.event)
e = window.event; if (String.fromCharCode(e.keyCode) == 'P' &
e.shiftKey & e.ctrlKey)
faceletsDebug('/facelettag/pages/debug/debug.jsf?
facelets.ui.DebugOutput=1179482643961'); else if (faceletsOrigKeyup)
faceletsOrigKeyup(e); };
//]]>
</script>
</body>
</html>
This tag contains only one attribute :
hotkey : This attribute is used to specify the key which is to be pressed with Ctrl+Shift to
open a debug window. Its default value is "d". It doesn't take EL expression.
Facelet decorate Tag

This tag is like composition tag. Difference between those is that the content outside of the
decorate tag is rendered while it is reverse for composition tag i.e. it is not rendered when we
use composition tag. This tag is useful when we want content with some decoration text in the
document.
decorate.xhtml:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<body>
<center><h2>RoseIndia Facelet Tags Tutorial</h2></center>
<h3>Welcome to the Facelet world..........</h3><hr/>

<ui:decorate template="/pages/decorate/decoratetemplate.xhtml">
<ui:define name="face1">
<table border="1">
<tr bgcolor="pink"><th>First Name</th>
<th>Last Name</th></tr>
<tr><td>Rose</td>
<td>India</td></tr>
<tr><td>Mr. Deepak</td>
<td>Kumar</td></tr>
</table><hr/>
</ui:define>
</ui:decorate>

<h3>This is the content below decorate tag.</h3>


</body>
</html>
decoratetemplate.xhtml :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets">
<head>
<title>facelet example </title>
<link href="../../style/CSS.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<ui:insert name="face1"></ui:insert>
</body>
</html>
Rendered Output :
Html Source Code :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >

<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<center><h2>RoseIndia Facelet Tags Tutorial</h2></center>
<h3>Welcome to the Facelet world..........</h3>
<hr /><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>facelet example </title>
<link href="../../style/CSS.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table border="1">
<tr bgcolor="pink">
<th>First Name</th>
<th>Last Name</th></tr>
<tr><td>Rose</td>
<td>India</td></tr>
<tr><td>Mr. Deepak</td>
<td>Kumar</td></tr>
</table><hr />
</body>
</html>
<h3>This is the content below decorate tag.</h3>
</body>
</html>
This tag contains one attribute :
template : This is used to specify the name of the template where the content of decorate tag
will be used .
Facelet define Tag

This tag is used to define the name of the content. This named content can be included within
a template. This tag is used within those tags that allows templating like composition and
decorate tags. This tag takes one attribute named "name" that is required to be included
when using this define tag. This name attribute is required to be same as name attribute of
insert tag in the target template to include the content specified in define tag with the same
name. For example, In the first define tag name attribute is set to "face1". Now look at the
code below in "definetemplate.xhtml" where we have used insert tag with name attribute.
This name attribute is given value "face1". So the content within define tag, whose name
attribute value matches with the name attribute of the insert tag i.e."face1", will be included
in the "definetemplate.xhtml".
Code Description :

define.xhtml :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<body>
Content above composition tag will not be rendered.
<ui:composition template="/pages/define/definetemplate.xhtml">
<ui:define name="face1">
<center><h2>RoseIndia Facelet Tags Tutorial</h2></center>
<h3>Welcome to the Facelet world..........</h3>
</ui:define>
<ui:define name="face2">Enter UserID :<br/>
<h:inputText id="it" /><br/><br/>
</ui:define>
<ui:define name="face3">Enter Password :<br/>
<h:inputSecret id="is" /><br/><br/>
</ui:define>
<ui:define name="face4">
<h:commandButton id="cb" value="Submit" />
</ui:define>
</ui:composition>
Content below composition tag will not be rendered.
</body>
</html>
definetemplate.xhtml :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets">
<head>
<title>facelet example </title>
<link href="../../style/CSS.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<ui:insert name="face1"> </ui:insert>
<ui:insert name="face2"> </ui:insert>
<ui:insert name="face3"> </ui:insert>
<ui:insert name="face4"> </ui:insert>
</body>
</html>
Rendered Output :

Html Source Code :


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd" >

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>facelet example </title>
<link href="../../style/CSS.css" rel="stylesheet" type="text/css" />
</head>
<body>
<center><h2>RoseIndia Facelet Tags Tutorial</h2></center>
<h3>Welcome to the Facelet world..........</h3>
Enter UserID :<br /><input id="it" type="text" name="it" /><br
/><br />
Enter Password :<br />
<input id="is" type="password" name="is" value="" /><br /><br />
<input id="cb" type="submit" name="cb" value="Submit" />
</body>
</html>
This tag contains only one attribute :
name : This attribute is used to give the name of the content specified in the define tag. This
value of name attribute must be same as name attribute in insert tag if its content is to be
included in the template.

Facelet fragment Tag

This tag is used to insert the new UIcomponent to the component tree and the content outside
of the tag is included to the tree. So this tag is same with component tag as decorate tag is with
composition tag i.e. as decorate tag behaves same as composition tag except including content
outside the tag, in the same way fragment tag behaves same as component tag except
including content outside the tag. In this example, the content within fragment tag in included
in component tree and the code above fragment tag is also rendered. So "Content above
fragment tag will be rendered." and "Content below fragment tag will be rendered." is
rendered.
Code Description :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets">
<head>
<title>facelet example </title>
</head>
<body>
<h3>Content above fragment tag will be rendered.</h3>
<ui:fragment >
<h4>This is the content to be included in the page.</h4>
</ui:fragment >
<h3>Content below fragment tag will be rendered.</h3>
</body>
</html>
Rendered Output :

Html Source Code :


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<title>facelet example </title>
</head>
<body>
<h3>Content above fragment tag will be rendered.</h3>
<h4>This is the content to be included in the page.</h4>
<h3>Content below fragment tag will be rendered.</h3>
</body>
</html>
This tag contains two attributes :
id : This attribute assigns unique identity to the component. Its not a required attribute. So if
you don't give id then facelet provides it automacally.
binding : This attribute is used to bind the component to the backing bean property.
Facelet include Tag

This tag is used to include the content of a page. This page name is specified by src attribute
of include tag. The page that has been included should use composition tag or component tag.
It may contain xhtml or xml to be included. In the program below, we have used include tag
and src attribute is set to "includepage.xhtml". So the content of this page will be included in
the "include.xhtml" page and rendered in "includetemplate.xhtml" because insert tag with
name attribute set to face5 is used in "includetemplate.xhtml".
include.xhtml:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<body>
Content above composition tag will not be rendered.
<ui:composition template="/pages/include/includetemplate.xhtml">
<ui:define name="face1">
<center><h2>RoseIndia Facelet Tags Tutorial</h2></center>
<h3>Welcome to the Facelet world..........</h3>
</ui:define>
<ui:define name="face2">Enter UserID :<br/>
<h:inputText id="it" /><br/><br/>
</ui:define>
<ui:define name="face3">Enter Password :<br/>
<h:inputSecret id="is" /><br/><br/>
</ui:define>
<ui:define name="face4">
<h:commandButton id="cb" value="Submit" />
</ui:define>
<ui:define name="face5">
<ui:include src="includepage.xhtml"/>
</ui:define>
</ui:composition>
Content below composition tag will not be rendered.
</body>
</html>
includetemplate.xhtml :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets">
<head>
<title>facelet example </title>
<link href="../../style/CSS.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<ui:insert name="face1"> </ui:insert>
<ui:insert name="face2"> </ui:insert>
<ui:insert name="face3"> </ui:insert>
<ui:insert name="face4"> </ui:insert>
<ui:insert name="face5"> </ui:insert>
</body>
</html>
includepage.xhtml : The content in this page that will be included in the
"includetemplate.xhtml"
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets">

<ui:composition>
<br/><br/>This is the content of <b>"includepage.xhtml"</b>
</ui:composition>

</html>
Rendered Output :

Html Source Code :


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd" >

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>facelet example </title>
<link href="../../style/CSS.css" rel="stylesheet" type="text/css" />
</head>
<body>
<center><h2>RoseIndia Facelet Tags Tutorial</h2></center>
<h3>Welcome to the Facelet world..........</h3>
Enter UserID :<br /><input id="it" type="text" name="it" /><br
/><br />
Enter Password :<br /><input id="is" type="password"
name="is" value="" /><br /><br />
<input id="cb" type="submit" name="cb" value="Submit" />
<br /><br />This is the content of <b>"includepage.xhtml"</b>
</body>
</html>
This tag contains only one attribute :
src : This is the required attribute that can be a litral or EL expression. This value must specify
a facelet whose content will be included in your template document.

Facelet insert Tag

This tag is used to replace the content defined in another facelet to the template. This tag takes
one attribute that is not a required attribute and is used in conjunction with define tag. If you
set this attribute same as defined in define tag then that content within define tag will be
included. If it doesn't match then the content specified within opening and closing tag of this
insert tag will be displayed. For example, in the code below in "insert.xhtml" there is not any
define tag whose name attribute value is "face5" and this value is used in the second file
"inserttemplate.xhtml". So the content ("This is the default text rendered") specified
within opening and closing tag of insert tag is displayed. While there is one insert tag whose
value of name attribute ("face1") matches with that of define tag, so the content "RoseIndia
Facelet Tags Tutorial" and "Welcome to the Facelet world.........." will be replaced to the
insert tag.

insert.xhtml :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<body>
Content above composition tag will not be rendered.
<ui:composition template="/pages/insert/inserttemplate.xhtml">
<ui:define name="face1">
<center><h2>RoseIndia Facelet Tags Tutorial</h2></center>
<h3>Welcome to the Facelet world..........</h3>
</ui:define>
<ui:define name="face2">Enter UserID :<br/>
<h:inputText id="it" /><br/><br/>
</ui:define>
<ui:define name="face3">Enter Password :<br/>
<h:inputSecret id="is" /><br/><br/>
</ui:define>
<ui:define name="face4">
<h:commandButton id="cb" value="Submit" />
</ui:define>
</ui:composition>
Content below composition tag will not be rendered.
</body>
</html>
inserttemplate.xhtml :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets">
<head>
<title>facelet example </title>
<link href="../../style/CSS.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<ui:insert name="face1"> </ui:insert>
<ui:insert name="face2"> </ui:insert>
<ui:insert name="face3"> </ui:insert>
<ui:insert name="face4"> </ui:insert>
<ui:insert name="face5"><h3>This is the default text
rendered</h3> </ui:insert>
</body>
</html>
Rendered Output :
Html Source Code :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd" >

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>facelet example </title>
<link href="../../style/CSS.css" rel="stylesheet" type="text/css" />
</head>
<body>
<center><h2>RoseIndia Facelet Tags Tutorial</h2></center>
<h3>Welcome to the Facelet world..........</h3>
Enter UserID :<br /><input id="it" type="text" name="it" /><br
/><br />
Enter Password :<br /><input id="is" type="password" name="is"
value="" /><br /><br />
<input id="cb" type="submit" name="cb" value="Submit" />
<h3>This is the default text rendered</h3>
</body>
</html>
This tag contains only one attribute :
name : This attribute is used to give the name of the content to be included in template. This
value of name attribute must be same as name attribute in define tag. If name value specified
here doesn't match with any name attribute specified in define tag then the content specified
within opening and closing tag of this insert tag will be displayed. This has been explained in
the above example.
Facelet param Tag

This tag is used to pass objects as variables between facelets. This tag has two required
attributes name and value. name attribute is the name of the variable and the value attribute is
to set the value of this variable. You can use this tag where a define tag is used within
composition or decorate tag. We can also use this tag within include tag. In this example, we
have taken two variables user and pwd within include tag in debug.xhtml and values are set
through bean's properties userid and password. These variable are passed to the
"includeparampage.xhtml" where we can use these variables in this line of code "Your
#{user} and #{pwd} will not be disclosed".
Code Description :

debug.xhtml :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<body>
Content above composition tag will not be rendered.
<ui:composition template="/pages/param/paramtemplate.xhtml">
<ui:define name="face1">
<center><h2>RoseIndia Facelet Tags Tutorial</h2></center>
<h3>Welcome to the Facelet world..........</h3>
</ui:define>
<ui:define name="face2">Enter UserID :<br/>
<h:inputText id="it" /><br/><br/>
</ui:define>
<ui:define name="face3">Enter Password :<br/>
<h:inputSecret id="is" /><br/><br/>
</ui:define>
<ui:define name="face4">
<h:commandButton id="cb" value="Submit" />
</ui:define>
<ui:define name="face5">
<ui:include src="includeparampage.xhtml">
<ui:param name="user"
value="#{MessageBean.userid}"/>
<ui:param name="pwd"
value="#{MessageBean.password}"/>
</ui:include>
</ui:define>
</ui:composition>
Content below composition tag will not be rendered.
</body>
</html>
debugtemplate.xhtml :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets">
<head>
<title>facelet example </title>
<link href="../../style/CSS.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<ui:insert name="face1"> </ui:insert>
<ui:insert name="face2"> </ui:insert>
<ui:insert name="face3"> </ui:insert>
<ui:insert name="face4"> </ui:insert>
<ui:insert name="face5"></ui:insert>
</body>
</html>
includeparampage.xhtml :
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0
Transitional//EN"
"http://www.w3.org/TR/xhtml
1/DTD/xhtml1-
transitional.dtd">
<html
xmlns="http://www.w3.org/19
99/xhtml"
xmlns:ui="http://java.sun.com/
jsf/facelets">

<ui:composition>
<br/><br/><h3>Your #{user}
and #{pwd} will not be
disclosed.</h3>
</ui:composition>

</html>
Rendered Output :
Html Source Code :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd" >

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>facelet example </title>
<link href="../../style/CSS.css" rel="stylesheet" type="text/css" />
</head>
<body>
<center><h2>RoseIndia Facelet Tags Tutorial</h2></center>
<h3>Welcome to the Facelet world..........</h3>
Enter UserID :<br /><input id="it" type="text" name="it" /><br
/><br />
Enter Password :<br /><input id="is" type="password"
name="is" value="" /><br /><br />
<input id="cb" type="submit" name="cb" value="Submit" />
<br /><br /><h3>Your ID and Password will not be disclosed.</h3>
</body>
</html>
This tag contains two attributes :
name : This is required attribute and is used to specify the name of the variable to be passed to
other facelet.
value : This is required attribute to set the value of the variable specified by the name
attribute.
Facelet remove Tag

This tag is used to remove content within this tag from a facelet at compile time. This tag
don't have any attribute. This tag can be used with jsfc attribute which shows that the
particular tag will be removed. In this example, the line "This line will be removed" will be
removed from facelet at the time of compilation and so will not be displayed. In this example,
the line where jsfc attribute is used and set to the ui:remove is not considered for compilation
so input text box for this line of code will not be displayed.
Code Description :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<body>
<center><h2>RoseIndia Facelet Tags Tutorial</h2></center>
<h3>Welcome to the Facelet world..........</h3><hr/>

<ui:decorate template="/pages/remove/removetemplate.xhtml">
<ui:define name="face1">
<h3><h:outputText value="This is the text to be displayed."/></h3>
<input type="text" jsfc="h:inputText" value="This i/p box is
rendered" />
<input type="text" jsfc="ui:remove" value="IT" />
<ui:remove>This line will be removed</ui:remove>
</ui:define>
</ui:decorate>
<hr/><h3>This is the content below decorate tag.</h3>
</body>
</html>
Rendered Output :
Html Source Code :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >

<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<center><h2>RoseIndia Facelet Tags Tutorial</h2></center>
<h3>Welcome to the Facelet world..........</h3>
<hr /><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>facelet example </title>
<link href="../../style/CSS.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h3>This is the text to be displayed.</h3><input type="text"
name="_id7" value="This i/p box is rendered" />
</body>
</html>
<hr /><h3>This is the content below decorate tag.</h3>
</body>
</html>
This tag has no attribute.
Facelet repeat Tag
This tag is used to iterate over the list of items. The name of list of items is specified by the EL
expression in the value attribute of this tag. This tag contains two attributes "value" "name".
The literal name specified in the name attribute is used to iterate over the items. In this
example, we have used a bean named "TableBean" and info name is given to be used further.
For ex., info.id, info.name used in value attribute of inputText JSF tag where id and name are
attributes specified in bean. so here all id and names will be displayed.
Code Description :

repeat.xhtml :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<body>
<center><h2>RoseIndia Facelet Tags Tutorial</h2></center>
<h3>Welcome to the Facelet world..........</h3>
<hr/>
<ui:decorate template="/pages/repeat/repeattemplate.xhtml">
<ui:define name="face1">
<h3><h:outputText value="This is the list of ID and
Names."/></h3>
<ui:repeat value="#{TableBean.perInfoAll}" var="info">
<li>
<h:inputText value="#{info.id}" />
<h:inputText value="#{info.name}" />
</li>
</ui:repeat>
</ui:define>
</ui:decorate>
</body>
</html>
repeattemplate.xhtml :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets">
<head>
<title>facelet example </title>
<link href="../../style/CSS.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<ui:insert name="face1"></ui:insert>
</body>
</html>
TableBean.java :(Java Bean used for collection of items)
package roseindia;

public class TableBean {

private perInfo[] perInfoAll = new perInfo[]{


new perInfo(101, "CHANDAN", "9891444444", "aaa", 11111),
new perInfo(102, "RAVI", "9911666666", "bbb" ,22222),
new perInfo(103, "JOHN", "9313888888", "ccc", 33333),
new perInfo(104, "ANDREW", "9911222222", "ddd" , 44444),
new perInfo(105, "SYMONDS", "9313999999", "eee", 55555)
};

public perInfo[] getperInfoAll() {


return perInfoAll;
}

public class perInfo {


int id;
String name;
String phone;
String city;
int pin;

public perInfo(int id, String name, String phone, String city, int pin) {
this.id = id;
this.name = name;
this.phone = phone;
this.city = city;
this.pin= pin;
}
public int getid() {
return id;
}
public String getname() {
return name;
}
public String getphone() {
return phone;
}
public String getcity() {
return city;
}
public int getpin() {
return pin;
}
}
}
Rendered Output :

Html Source Code :


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml">

<body>
<center><h2>RoseIndia Facelet Tags Tutorial</h2></center>
<h3>Welcome to the Facelet world..........</h3>
<hr /><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/
TR/xhtml1/DTD/xhtml1-transitional.dtd" >

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>facelet example </title>
<link href="../../style/CSS.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h3>This is the list of ID and Names.</h3>
<li>
<input type="text" name="_id7:0:_id9" value="101" />
<input type="text" name="_id7:0:_id10" value="CHANDAN" />
</li>
<li>
<input type="text" name="_id7:1:_id9" value="102" />
<input type="text" name="_id7:1:_id10" value="RAVI" />
</li>
<li>
<input type="text" name="_id7:2:_id9" value="103" />
<input type="text" name="_id7:2:_id10" value="JOHN" />
</li>
<li>
<input type="text" name="_id7:3:_id9" value="104" />
<input type="text" name="_id7:3:_id10" value="ANDREW" />
</li>
<li>
<input type="text" name="_id7:4:_id9" value="105" />
<input type="text" name="_id7:4:_id10" value="SYMONDS" />
</li>
</body>
</html>
</body>
</html>
This tag contains two attributes :
value : This attribute specifies the list of items whose items are to be iterated. This is the EL
expression.
var : This attribute is used to give a name using that the iteration is done.
Installing JSF 1.1 in TOMCAT 5.5.23

In this section, we will learn about installation of JSF 1.1 to TOMCAT 5.5.23. Java Server
Faces (JSF) requires some steps to follow while configuring it in TOMCAT. Here we are
considering you comfortable installing the tomcat. There is nothing much to do to install JSF
if you have already installed and configured tomcat 5.5.23. We require
1. Jdk1.6.0
2. Tomcat 5.5.23
3. Jsf 1.1
4. Servlet 2.3
5. Jsp 1.2
The steps required to make your JSF application run are summarized below :
1. Download zip file of tomcat 5.5.23 from http://tomcat.apache.org/download-
55.cgi#5.5.23.
2. Extract this file to the directory of your choice (suppose c:/tomcat) (remember to set
JAVA_HOME variable).
You will get 9 sub-folders into this tomcat directory :
1)bin
2)common
3)conf
4)logs
5)server
6)shared
7)temp
8)web-apps
9)work
and some files.
3. Download zipped file of jsf 1.1 Reference Implementation from
http://java.sun.com/javaee/javaserverfaces/download.html.
4. Extract the above zipped file of jsf 1.1 to the directory of your choice (suppose c:/jsf).
You will get 7 sub-folders in this jsf folder :
1) docs
2) javadocs
3) lib
4) metadata
5) renderkitdocs
6) samples
7) tlddocs
and some files.
5. Copy all jar files from jsf/lib directory of above extracted file to tomcat/common/lib
directory.
6. Copy two jar files "jstl.jar" and "standard.jar" from tomcat/webapps/jsp-
examples/WEB-INF/lib directory to tomcat/common/lib directory.
7. Set class path for these jar files.
8. Start tomcat.
After configuring JSF in tomcat, we can create and run JSF application. After making any
changes in application, its better restart the tomcat before running the application. If you want
to run a sample application provided by JSF reference implementation then
1. go to jsf/samples folder
2. copy any war file from here to tomcat/webapps
3. restart tomcat server
This war file gets extracted automatically to the directory structure with the same name of war
file. Now you can run this application in tomcat and you can follow the directory structure of
these applications to make your own application. In this tutorial, all steps have been described
in simple manner by a simple application "SimpleHelloByEnteringName".
Simple JSF Hello Application
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 :
We will follow the following steps to create this application :
1. Create development directory structure (root directory and sub directories)
2. Create and place configuration files in appropriate place
3. Create JSP pages
4. Create a properties file
5. Create a managed bean
6. Register managed bean in configuration file
7. Define a navigation rule in configuration file
8. Run the application
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:

Directory structure of this application :


Application Name: SimpleHelloByEnteringName
Create and place directories, configuration files :
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 :
1. 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 the initial format of this file will be like this:
<?xml
version="1.0"?>
<web-app>
...................
...............
...................
...............
...................
...............
</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.
2. 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.
So initial format of this file will be like this:
<?xml
version="1.0"?>
<faces-config>
...................
..............
...................
..............
...................
..............
</faces-config>

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.
This JSF application contains:
1. Three JSP pages for viewing purpose
2. JavaBean to hold model data
3. Configuration files specifying managed bean, navigation rules, controller
servlet.
Now our first step is to create view for the application. For this we have created three JSP files
given below:
1. index.jsp
2. inputname.jsp
3. result.jsp

Creating JSP pages:


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:

inputname.jsp :
<%@ 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"/>

<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 :
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

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.

<f:loadBundle basename="roseindia.messages" var="message"/>


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

<h:inputText value="#{StoreNameBean.personName}" />


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.

<h:commandButton action="result" value="#{message.button_text}" />


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 :

result.jsp :
<%@ 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" page):

Now we come to those topics that has been left unexplained above.

Creating properties file (resource bundle) :


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=Ro
seindia JSF
Tutorial
prompt=Enter Your
Name:
greeting_text=Welco
me In Roseindia JSF
Tutorial
button_text=Submit

Creating Managed Bean :


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;

public class PersonBean {


String personName;
public String getPersonName() {
return personName;
}

public void setPersonName(String name) {


personName = name;
}
}

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:

Registering managed bean :


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>

<managed-bean> defines a managed bean. Bean'name is given in <managed-bean-


name>tag. This name is used in JSP files to represent the bean. The class name which
corresponds to this bean is given in <managed-bean-class> tag. To define the scope for the
bean we specify this in <managed-bean-scope> tag. In this Application name of the bean that
will be used in JSP files is StoreNameBean that is represented by the bean class PersonBean
in roseindia package.

Defining navigation rule :


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".
So after editing faces-config.xml file, it will look like following:
<?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>

<!-- Faces Servlet Mapping -->


<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>

<servlet> element is used to map the "javax.faces.webapp.FacesServlet" servlet class to a


symbolic name i.e. Faces Servlet is an alias for "javax.faces.webapp.FacesServlet" servlet .So
<servlet> tag registers the Faces servlet.<servlet-mapping> element is used to map any
request of pattern like .jsf in the URL must be passed to the Faces 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.
Running the application :
This application is now complete. To run this application start Tomcat server and type
http://localhost:8080/SimpleHelloByEnteringName URL in the address bar of your browser
and hit enter.
You can download the example and unzip it and paste SimpleHelloByEnteringName folder in
webapps folder and run it.
Downloading and Installing "SimpleHelloByEnteringName"
JSF Example

"SimpleHelloByEnteringName" JSF example. In this, we will show you how you can quickly
download and install the source code of the application provided by us. This will help you
start JSF easily without spending time in installing and configuring JSF application your self.
STEPS-
1. Download zip file of the "SimpleHelloByEnteringName" JSF application form here.
2. Extract the zip file anywhere. You will get a folder named
"SimpleHelloByEnteringName".
3. Download tomcat 5.5.23 or latest version and install it (I am assuming that you are
comfortable with tomcat installation)
4. Move the extracted file "SimpleHelloByEnteringName" to the webapps directory of
tomcat.
5. Run the tomcat
6. type http://localhost:8080/SimpleHelloByEnteringName in the address bar of browser
and click "go" or hit the enter key of keyboard
When you submit the request, you will see the result displayed on the browser like this :

Suppose you have filled name "rose" in the input text box in the above page, You will be
welcomed with your name like this :
This is the final output of this application. Now we expect that you can build your own
application that may be as simple as explained here or even complex. Here, it was an attempt
to provide you a simple structure of web application that makes you clear about directory
structure means where to place what and how to write code and mappings.
JSF Navigation By Example

Navigation means connected component and it's events each-another. This section illustrates
you about the JSF navigation by providing the example with the complete code of the
program. In the Roseindia JSF Tutorial you will see that the provided code of the example can
be executed directly by copying-paste in your JSF application or by downloading and
deploying it in your application according to the given procedure of the deployment or
implementation of program.
Roseindia JSF Tutorial here gives you the complete solution related to the example like from
copying or downloading program up to the executing it by following each and every steps of
the deployment during these processes.
By studying this example line-by-line, you can get more knowledge about the navigation of
pages. You can also get the answer of the question like how pages can be linked to the another
pages in the Java Server Faces Framework. This type of navigation are managed by the
controller i.e. the faces-config.xml file in JSF for controlling your whole web based JSF
application.
This tutorial is making introduction for the following files these have been used in the JSF
Navigation example as follows:
There are given two files have been used for showing how navigation of pages works in JSF.
For showing the main purpose you have to simply pass a value from the controller to navigate
to an another page. For this you have to make a navigation rule in the faces-config.xml file.
Files used for the example are given below:
• firstpage.jsp: This is the first pages of the application or example that shows a simple
command button has an action value that is sent to the controller when you click on the
button.

• secondpage.jsp: This page is referred by the controller (faces-config.xml) file according


to the action value which has been sent by the firstpage.jsp file after clicking the button
component of the page by you.
Here you saw the navigation between the fistpage.jsp and the secondpage.jsp files. Now you
will get the complete installation of the example on your system for running properly. Steps
are as follows:
You have to make some pages by copying
example code otherwise you can download
Steexamples directly and copy the application folder
p I:in the tomcat/webapps folder. This downloaded
file will be a war file that is automatically
deployed when you run the tomcat server if the
war file exists in the tomcat/webapps folder.
SteIf you making your own pages by copying all the
pcode of pages then you will have to deploy your
II: application according to the given suggestions
for the directory structure of the application.
SteThis step tells you for running the application
pwithout any hesitations. You can type the url:
III:http://localhost:8080/JSFNavigationExample/fi
rstpage.jsf.
Directory Structure for the Example:

Here is the source code of firstpage.jsp file:


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

<f:view>
<html>
<head><title>Navigation
Page</title></head>

<body>
<h1>This is the first
page.</h1>
<h:form>
<h:commandButton
value="Go to second page" action
="secondpage" />
</h:form>
</body>
</html>
</f:view>

Source Code of the secondpage.jsp file:


<h4>This page is navigated by the
firstpage.jsp
that has been mentioned in the faces-
config.xml file.</h4>
Source Code of the faces-config.xml file:
<?xml version="1.0" encoding="UTF-
8"?>
<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems,
Inc.//DTD JavaServer
Faces Config 1.0//EN"
"http://java.sun.com/
dtd/web-facesconfig_1_0.dtd">

<faces-config>
<navigation-rule>
<from-view-
id>/firstpage.jsp</from-view-id>
<navigation-case>
<from-
outcome>secondpage</from-outcome>
<to-view-
id>/secondpage.jsp</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
Source Code of the web.xml file:
<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems,
Inc.//DTD Web Application
2.3//EN" "http://java.sun.com/dtd/web-
app_2_3.dtd">

<web-app>
<context-param>
<param-
name>javax.faces.STATE_SAVING_METHOD</param-
name>
<param-value>server</param-value>
</context-param>

<!-- Faces Servlet -->


<servlet>
<servlet-name>Faces Servlet</servlet-
name>
<servlet-
class>javax.faces.webapp.FacesServlet</servlet-
class>
<load-on-startup> 1 </load-on-startup>
</servlet>

<!-- Faces Servlet Mapping -->


<servlet-mapping>
<servlet-name>Faces Servlet</servlet-
name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
</web-app>

JSF Static Navigation Example

This is a part of navigation in which one page is navigated to others. This section gives you
something about the JSF Static navigation which makes the direct navigation between two or
more pages. There is an example of Static Navigation in JSF has been implemented with the
complete downloadable solutions like the example code and the illustration about the
procedure of deployment of example. This type of the navigation navigate directly to the other
sources which have to mentioned as it is.
Here, you will find the code of the example and can get more about the static navigation in the
JSF application in very efficient manner. This type of navigation works like an anchor tag (<a
href=""></a>) of HTML (Hyper Text Markup Language).
There is an example has been given in this section for illustrating the topic more conveniently.
This example shows command button labeled with the text "Go to second page". When you
will click on the button pages is referred to an another page. This application uses some files
for completion the application as given as below:
• firstpage.jsp
• secondpage.jsp
Program Output as follows:
When you will click on the command button component it will show the output as follows:

Code for the firstpage.jsp file:


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

<f:view>
<html>
<head><title>Navigation Page</title></head>

<body>
<h1>This is the first page.</h1>
<h:form>
<h:commandButton value="Go to second page"
action="secondpage" />
</h:form>
</body>
</html>
</f:view>

Code for the secondpage.jsp file:


<h4>This page is navigated by the firstpage.jsp that has been mentioned in the
faces-config.xml file.</h4>

Code for the faces-config.xml file:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer
Faces Config 1.0//EN" "http://java.sun.com/dtd/web-facesconfig_1_0.dtd">

<faces-config>
<navigation-rule>
<from-view-id>/firstpage.jsp</from-view-id>
<navigation-case>
<from-outcome>secondpage</from-outcome>
<to-view-id>/secondpage.jsp</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>

Code for the web.xml file:


<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application
2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>

<!-- Faces Servlet -->


<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup> 1 </load-on-startup>
</servlet>

<!-- Faces Servlet Mapping -->


<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
</web-app>

JSF Global Navigation Example

This is a part of navigation in which one page is navigated to others. This section gives you
something about the JSF Global navigation which makes the direct navigation between two or
more pages. There is an example of Global Navigation in JSF has been implemented with the
complete downloadable solutions like the example code and the illustration about the
procedure of deployment of example. This type of the navigation navigate directly to the other
sources which have to mentioned as it is.
Here, you will find the code of the example and can get more about the global navigation in
the JSF application in very efficient manner. This type of navigation does not works like an
anchor tag (<a href=""></a>) of HTML (Hyper Text Markup Language). This type of
navigation is shown by implementing the example in this section. There is the page that has to
be referred in the example has been mentioned in the faces-config.xml file that is is handled
by the action of the command button of the form from the page. You can see that the module
of the code which is written in the faces-config.xml file that is like as follows:
<navigation-rule>
<from-view-id>*</from-view-id>
<navigation-case>
<from-outcome>secondpage</from-outcome>
<to-view-id>/secondpage.jsp</to-view-id>
</navigation-case>
</navigation-rule>
Above code makes the navigation rule in which the page and the action is mentioned. As you can
see the value of the <from-view-id></from-view-id> is the "*" and the value of the <from-
outcome></from-outcome> tage is "secondpage" which is the action of the command button and
referred page is mentioned as the value of the <to-view-id></to-view-id> tag that mean the
secondpage.jsp page can be referred on the occurring of the action "secondpage" from any page
involved in the application which is determined by the "*" value.
There is an example has been given in this section for illustrating the topic more conveniently.
This example shows command button labeled with the text "Go to second page". When you
will click on the button pages is referred to an another page. This application uses some files
for completion the application as given as below:
• firstpage.jsp
• secondpage.jsp
Program Output as follows:

When you will click on the command button component it will show the output as follows:
Code for the firstpage.jsp file:
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<f:view>
<html>
<head><title>Navigation Page</title></head>

<body>
<h1>This is the first page.</h1>
<h:form>
<h:commandButton value="Go to second page"
action="secondpage" />
</h:form>
</body>
</html>
</f:view>

Code for the secondpage.jsp file:


<h4>This page is navigated by the firstpage.jsp that has been mentioned in the
faces-config.xml file.</h4>

Code for the faces-config.xml file:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer
Faces Config 1.0//EN" "http://java.sun.com/dtd/web-facesconfig_1_0.dtd">

<faces-config>
<navigation-rule>
<from-view-id>*</from-view-id>
<navigation-case>
<from-outcome>secondpage</from-outcome>
<to-view-id>/secondpage.jsp</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>

Code for the web.xml file:


<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web
Application
2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>

<!-- Faces Servlet -->


<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup> 1 </load-on-startup>
</servlet>

<!-- Faces Servlet Mapping -->


<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
</web-app>

JSF Search Application Using Ajax

Here, Roseindia Tutorial Section provides you a JSF search application using Ajax. This is a
simple application in which, you will see two JSF components that one is the text box
component which is for entering keywords whatever you have to search and second one is the
command button labeled with the "OK" text that is for submitting the form by clicking on that
component. When you enter the keyword into the text box component for searching about the
the keyword i.e. the title of the topic provided by the Roseindia Java Tutorial, during entering
each and every character of the title this component shows you a popup below the text box
component that holds some titles starting with the entered text into the text box component.
This application is very useful for everybody who want to integrate into the any type of
website. You can direct copy the given code and paste it into your application for constructing
the application.
Search application in any type website makes the website reliable and very user friendly for
visitors. Visitors can direct search the topic and getting the detailed explanation of the title for
learning more. This application here using JSF and AJAX technology that mean this is based
on the JSF and the AJAX technology. You can get the more about the JSF like what is JSF?
and how does it work? in the Roseindia JSF Tutorial. This tutorial gives you the complete JSF
tutorial from the starting point of the JSF to the professional level programming in JSF. You
will just learn here about the integrating or using AJAX in the JSF. This section tells you
about the procedure of using AJAX in JSF by providing the complete code for viewing and
download also.
This section here introduces about the JSF and the AJAX technology:
AJAX: Ajax stands for Asynchronous JavaScript and XML. Ajax is used to fetch the data
from web server without refreshing the whole page. JavaScript is used to send the request to
web server in order to fetch the data. You can know more about the Ajax technology in detail
by visiting the Roseindia Ajax Tutorial.
There are some JSP pages for viewing the the page by providing the JSF syntaxes, some Java
Bean Classes for holding data temporarily, Servlet for handling the AJAX operation and a file
that is for holding all data like the titles of the tutorial with the link regarding that and the full
description also regarding the title of the topic have used for building the complete
application. These files are illustrated as follows one by one:
Following some file names these have been used in the application:
• index.jsp
• search.jsp
• web.xml
• faces-config.xml
• AjaxServlet.java
• TitleBean.java
• TitleRecord.java
• SelectedTitleRecord.java
• script.js
Directory structure of the application is pictured as follows:

Here is the code of the index.jsp page:


<jsp:forward page="/search.jsf" />
Here is the code of for the search.jsp page:
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<html>
<head>
<title>Roseindia Search Page</title>
<style type="text/css">
.box { position:absolute;border: 1px
solid #000000; }
.result {
cursor:pointer;
}

.title {
font-family: Georgia, "Times
New Roman", Times, serif;
font-weight: bold;
font-size: 24px;
}
.heading {
font-family: Georgia, "Times New Roman", Times
, serif;
font-weight: bold;
font-size: 16px;
}
</style>
<script type="text/javascript" language="JavaScript" src="js/script.js">
</script>
</head>

<body onload="initialize();">
<f:view>
<h:form>
<h:outputText value="Roseindia Search Application"
styleClass="title"/><br><br>
<h:outputText value="Tutorial Search: " />
<h:inputText id="autoText" onblur="hidePopup()" onfocus=
"getQuery(this.value)" onkeyup="getQuery(this.value)" value="#{SelectedTitleRecord.
selectedTitle}" />
<h:commandButton value="OK" action=""/>
<hr>
<table>
<tr>
<td>
<h:outputText styleClass="heading"
value="Title Details" rendered="#{SelectedTitleRecord.selected}" />
</td>
</tr>
<tr>
<td><b>
<h:outputLink value=
"#{SelectedTitleRecord.link}">
<h:outputText value=
"#{SelectedTitleRecord.titlename}" />
</h:outputLink></b>
</td>
</tr>
<tr>
Here is the code for the script.js file:
var req;

if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}

var popupBoxName, textBoxName;

function initPopup(tBox, popupBox){


popupBoxName = popupBox;
textBoxName = tBox;
var popupLayer = document.getElementById(popupBox).style;
var qText = document.getElementById(tBox);

qText.setAttribute('autocomplete','off');
var x = findPosX(qText);
var y = findPosY(qText);

var width = getWidth(qText);


popupLayer.left = x + "px";
popupLayer.top = (y + 22) +"px";

popupLayer.width = width;
}

function doMouseClick(val){
hidePopup();
var qText = document.getElementById(textBoxName);
qText.value = val;
}

function hidePopup(){
var popupLayer = document.getElementById(popupBoxName).style;
popupLayer.visibility="hidden";
}

function showPopup(){
var popupLayer = document.getElementById(popupBoxName).style;
popupLayer.visibility="visible";
}

function getQuery(key) {
if (key=="") {
hidePopup();
return;
}
if (req.readyState != 0) {
req.abort();
}

var url = "/jsfajax/AjaxServlet?key=" + key;


if (req != null) {
req.open("GET", url, true);
req.onreadystatechange = processResponse;
req.send(null);
}
}

function processResponse() {
if (req.readyState == 4){
if (req.status == 200) {
if(req.responseText==null) {
hidePopup();
}
else {
parseResponse(req.responseText);
}
}
}
}

function parseResponse(result){
var xmlDoc;
if(document.implementation && document.implementation.createDocument) {
xmlDoc = document.implementation.createDocument("", "", null);
xmlDoc.async="false";
xmlDoc.loadXML(result);
} else if (window.ActiveXObject){
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(result);
}
var count = xmlDoc.getElementsByTagName("TOTALCOUNT").item(0).getAttribute("count")

if(count != "0"){
var fldValues = xmlDoc.getElementsByTagName("TITLE");
var fldResult='';
var values11 = new Array();
for (var i=0;i<fldValues.length;i++){
var val = fldValues.item(i).getAttribute("name");
fldResult += '<SPAN class="result" onmouseover="this.style.color=
\'blue\';" onmouseout="this.style.color=\'black\';" onmousedown="doMouseClick(\'' + val +
'\');" >' + val + '</SPAN><BR>';
}
document.getElementById("autocomplete").innerHTML = fldResult;
showPopup();
} else {
hidePopup();
}
}

var isIE = (window.navigator.appName.toLowerCase().indexOf("microsoft")>=0);

if(!isIE){
Document.prototype.loadXML = function (s) {
var doc2 = (new DOMParser()).parseFromString(s, "text/xml");
while (this.hasChildNodes())
this.removeChild(this.lastChild);

for (var i = 0; i < doc2.childNodes.length; i++) {


this.appendChild(this.importNode(doc2.childNodes[i], true));
}
};
}

function findPosX(obj){
var curleft = 0;
if (obj.offsetParent){
while (obj.offsetParent){
curleft += obj.offsetLeft
obj = obj.offsetParent;
}
}
else if (obj.x)
curleft += obj.x;
return curleft;
}

function findPosY(obj){
var curtop = 0;
if (obj.offsetParent){
while (obj.offsetParent){
curtop += obj.offsetTop
obj = obj.offsetParent;
}
}
else if (obj.y)
curtop += obj.y;
return curtop;
}

function getWidth(element){
if (element.clientWidth && element.offsetWidth && element.clientWidth <element.
offsetWidth) {
return element.clientWidth;
} else if (element.offsetWidth) {
return element.offsetWidth;
} else if (element.width) {
return element.width;
} else {
return 0;
}
}
Here is the code of the AjaxServlet.java file:
package roseindia;

import java.io.*;
import java.sql.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class AjaxServlet extends HttpServlet {


private ServletConfig servletConfig = null;
public void destroy() {
servletConfig = null;
}

public ServletConfig getServletConfig() {


return (this.servletConfig);
}

public String getServletInfo() {


return (this.getClass().getName());
}

public void init(ServletConfig servletConfig) throws ServletException{


this.servletConfig = servletConfig;
}

public void doGet(HttpServletRequest request, HttpServletResponse response) throws jav


.io.IOException, ServletException{
String key = (String)request.getParameter("key");
TitleBean titleBean = (TitleBean)getServletContext().getAttribute("TitleBean");
String[] titles = titleBean.getTitles();
String matches = getMatches(titles, key);
response.setContentType("text/xml");
java.io.PrintWriter out=response.getWriter();
out.print(matches);
out.flush();
}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ja


.io.IOException, ServletException {
doGet(request, response);
}

private String getMatches(String[] titles, String key){


String cList = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
cList +="<TITLES>";
int count = 0;
for(int i=0;i<titles.length;i++){
if(titles[i].toUpperCase().startsWith(key.toUpperCase())){
cList += "<TITLE name=\"" + titles[i] + "\" />";
count++;
if(count == 5) break;
}
}
cList += "<TOTALCOUNT count=\"" + count + "\" />";
cList += "</TITLES>";
return cList;
}
}

Here is the code of the TitleBean.java file:


package roseindia;

public class TitleBean{


String[] titles;
java.util.HashMap titleDetails = new java.util.HashMap();

public static void main(String[] args){


TitleBean tb = new TitleBean();
}

public TitleBean(){
try{
System.out.println("Reading data from the file...");
java.io.BufferedReader in=new java.io.BufferedReader(new java.io.InputStreamReade
TitleBean.this.getClass().getResourceAsStream("title.data")));
readData(in);
in.close();

} catch (java.io.IOException IOex) {


System.out.println("IO Error :" +IOex);
}
}

public java.util.HashMap getTitleDetails(){


return titleDetails;
}

public String[] getTitles(){


return titles;
}
private void readData(java.io.BufferedReader br) throws java.io.IOException {
int recordNum= Integer.parseInt(br.readLine());
titles = new String[recordNum];
for(int i=0; i<recordNum; i++){
String line=br.readLine();
java.util.StringTokenizer st=new java.util.StringTokenizer(line, "\t\r");
String titlename= st.nextToken();
String description= st.nextToken();
String cont = st.nextToken();
TitleRecord cr= new TitleRecord(titlename, description, cont);
titleDetails.put(titlename, cr);
titles[i] = titlename;
}
}
}

Here is the code of the TitleRecord.java file:


package roseindia;

public class TitleRecord {


String titlename;
String description;
String link;
// String capital;
// String id;

public TitleRecord(String titlename, String description, String link){


this.titlename=titlename;
this.description=description;
this.link=link;
// this.capital = capital;
// this.id=id;
}

public String getTitlename(){


return titlename;
}

public String getDescription(){


return description;
}

public String getLink(){


return link;
}
}

Here is the code of the SelectedTitleRecord.java file:


package roseindia;

public class SelectedTitleRecord{


String selectedTitle;
TitleRecord selectedTitleRecord;
java.util.HashMap titleDetails;

public SelectedTitleRecord(){
setTitleDetails();
}

public String getSelectedTitle(){


return selectedTitle;
}
public void setSelectedTitle(String selectedTitle){
this.selectedTitle = selectedTitle;
setSelectedTitleRecord();
}

public String getTitlename(){


if(selectedTitleRecord != null) return selectedTitleRecord.getTitlename();
else return null;
}
public String getDescription(){
if(selectedTitleRecord != null) return selectedTitleRecord.getDescription
();
else return null;
}

public String getLink(){


if(selectedTitleRecord != null) {
if (selectedTitleRecord.getLink() != "") {
String link = selectedTitleRecord.getLink().toLowerCase();
return link;
}
}
return null;
}
public boolean isSelected(){
if(selectedTitleRecord != null) return true;
else return false;
}
public void setSelectedTitleRecord(){
if(selectedTitle != null) {
Object obj = titleDetails.get(selectedTitle);
if((obj != null) && (obj instanceof TitleRecord)){
selectedTitleRecord = (TitleRecord) obj;
} else selectedTitleRecord=null;
} else selectedTitleRecord = null;
}

public void setTitleDetails(){


javax.faces.context.FacesContext context = javax.faces.context.FacesConte
xt.
getCurrentInstance();
javax.faces.application.Application app = context.getApplication();
TitleBean cBean = (TitleBean) app.createValueBinding("#{TitleBean}").getV
alue(context);
titleDetails = cBean.getTitleDetails();
}
}

Here is data in the title.data file:


1 2
2 Java Tutorial This is the Roseindia Java Tutorial providing the
complete java
solutions. This Tutorial gives you the complete java tutorial with some
example which is
ready to execute directly. http://www.roseindia.net/java/
3 Java Swing Tutorial This tutorial gives you the complete java swing
tutorial.
http://www.roseindia.net/java/example/java/swing
Managing Bean Example

This section describes you the use of the managed bean in an JSF application. In an JSF
application, backing beans (managed beans) are used that can be associated with UI
components. Backing Beans are nothing but JavaBeans which defines properties and methods.
These properties are bound to component values or component instances. setX() and getX()
methods are defined and implemented for all properties. We can also define methods that can
be used for different purpose like event handling, navigation, validation etc. that are associated
with component. To bind value of the component to the property of the bean or to refer
method of the bean from component tag, Expression Language (EL) syntax is used. For
example, #{BeanName.propertyName}can be used to bind the value of the component to the
property "propertyName" of the bean "BeanName". #{BeanName.methodName} can be
used to refer method "methodName()" of the bean "BeanName".
This tutorial explains how backing bean can be used in our application "managedbean". In
this application "Bean.java" is backing bean which has been used further in view pages. We
have saved this JavaBean file in WEB-INF\classes\roseindia directory of this application.
Step1 : Create a JavaBean file "Bean.java".
package roseindia;

public class Bean{


private String thought_of_the_day;
private String userName;
private String phoneNo;
private String company;

public void setThought_of_the_day(String thought_of_the_day){


this.thought_of_the_day=thought_of_the_day;
}
public void setUserName(String userName){
this.userName=userName;
}

public void setPhoneNo(String phoneNo){


this.phoneNo=phoneNo;
}

public void setCompany(String company){


this.company=company;
}

public String getThought_of_the_day(){


return thought_of_the_day;
}
public String getUserName(){
return userName;
}

public String getPhoneNo(){


return phoneNo;
}

public String getCompany(){


return company;
}

public String selectPage(){


if(company.equals("RoseIndia")){
return "rose";
}
else{
return "other";
}
}
}

In the above file, there are four properties "thought_of_the_day", "useName", "phoneNo",
"company" and setter and getter methods for each property to get and set values for the
components respectively . There is one more method selectPage() that returns "rose" and
"other" strings according to the condition.
Step2 : Configure the configuration file "faces-config.xml". Just add lines given below in this
file. To configure the bean in configuration file <managed-bean> element is used. Its child
element <managed-bean-name> is used to give the name of the bean to be used in the
application to refer the bean class specified in another child element <managed-bean-class>.
We can also specify the property value in the configuration file. For this <managed-property>
child element is used where its child element <property-name> specifies the name of the
property and <value> specifies its value.
<managed-bean>
<managed-bean-name>Bean</managed-bean-name>
<managed-bean-class>roseindia.Bean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>thought_of_the_day</property-name>
<value>It's good to be important but it's more important
to be good.
</value>
</managed-property>
</managed-bean>
For navigation purpose add following lines to the configuration file.
<navigation-rule>
<from-view-id>/pages/user.jsp</from-view-id>
<navigation-case>
<from-outcome>rose</from-outcome>
<to-view-id>/pages/welcome.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>other</from-outcome>
<to-view-id>/pages/otherpage.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/pages/welcome.jsp</from-view-id>
<navigation-case>
<from-outcome>Edit</from-outcome>
<to-view-id>/pages/user.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/pages/otherpage.jsp</from-view-id>
<navigation-case>
<from-outcome>back</from-outcome>
<to-view-id>/pages/user.jsp</to-view-id>
</navigation-case>
</navigation-rule>
Step3 : Now we are ready to create view pages and use bean properties and methods in the
application . In this example, we have three JSP pages "user.jsp", "welcome.jsp",
"otherpage.jsp" in the "pages" directory within the application home directory.
user.jsp :
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<html>
<head><title>Managed Bean Example(User Page)</title></head>
<body>
<f:view>
<h:form>
&nbsp;&nbsp;<h:outputText value="User Name." /><br>
&nbsp;&nbsp;<h:inputText value="#{Bean.userName}"/><br><br>
&nbsp;&nbsp;<h:outputText value="Phone No." /><br>
&nbsp;&nbsp;<h:inputText value="#{Bean.phoneNo}" /><br><br>
&nbsp;&nbsp;<h:outputText value="Company Name" /><br>
&nbsp;&nbsp;<h:inputText value="#{Bean.company}" /><br><br>
&nbsp;&nbsp;<h:outputText value="Thought of the day" /><br>
&nbsp;&nbsp;<h:inputText
value="#{Bean.thought_of_the_day}" />
<h:commandButton value="Submit" action="#{Bean.selectPage}" />
</h:form>
</f:view>
</body>
</html>
In this page we have associated values of the UIcomponents to the backing bean's properties.
This binding has been shown by bold letters. userName, phoneNo, company,
thought_of_the_day properties are bound to the input components. When the user first calls
this page, the last input component will be shown with the value specified in the "faces-
config.xml" file because we have already specified this value in the configuration file. When
the user fills values in these components these values are stored in the properties of the bean.
So when they are again bound with the component, stored values are used. For example, in
"welcome.jsp" page we have again used these properties values so it considers the values
filled in previous page. Command button component's action is associated with selectPage()
method of the Bean class. This method returns a String value either "rose" or "other". This
value is set to the action attribute of the commandButton tag. This button works according to
the returned value and the navigation rules specified in the "faces-config.xml" file.
welcome.jsp :
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<html>
<head><title>Managed Bean Example (Welcome page)</title></head>
<body>
<f:view>
<h:form>
<h:outputText value="You have entered :" /><hr>User Name :
<h:outputText value="#{Bean.userName}" /><br> Password :
<h:outputText value="#{Bean.phoneNo}" /><br> Phone No :
<h:outputText value="#{Bean.company}" /><br>
<h:commandButton value="Edit Details" action="Edit"/><hr>
<h:outputText value="#{Bean.thought_of_the_day}" /></b>
</h:form>
</f:view>
</body>
</html>
otherpage.jsp :
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<html>
<head><title>Managed Bean Example (otherpage page)</title></head>
<body>
<f:view>
<h:form>
<h:outputText value="Sorry........This is for RoseIndia
employees only. " /><br>
<h:commandButton value="Go Back" action="back"/>
</h:form>
</f:view>
</body>
</html>
Output : This is the first page which has four input boxes and one submit button. Last input
box already contains some text which comes from the value specified in the configuration file.
Now suppose user fills values as shown below :
The page below comes if the user fills Company Name as "RoseIndia".

The page below comes if user doesn't fill Company Name as "RoseIndia".

JSF Simple Login Application

This is the login application in which you will get the complete login facilities whatever
should be in a web based application for protecting the page or the website accessibility. This
application provides authentication for accessing application after successful login. For
accessing the application everyone should have a user id and a password regarding of that.
This application is very useful for developing any type of web based application in which
login application is needed. Here Roseindia provides you a complete login application in the
JSF Tutorial section to teach you JSF by examples. You are here after getting all the
theoretical concepts from the previous section of the Roseindia JSF Tutorial. If you have
already completed all the theoretical concepts from the Roseindia JSF Tutorial then OK
otherwise first you should complete previous sections from the Roseindia JSF Tutorial.
Here, you are going to study the JSF Login Application that is simply for the login purpose
that illustrates you about the procedure of developing applications in JSF. You will know how
JSF works after following the example.
This section here provides you a simple but the important thing for protecting your any type of
web application that makes your website or application secure. This application is simply used
for providing the facility for accessing the application by getting authentication.
When you run the application, this application will tell you for entering your login Id and
Password. If you enter wrong login id or password it will show you for "Login failed!" and if
you enter the correct login id and password then the application shows the message "Login
Successful!". For logging the application first you have to know your login id and password
which are given as follows:
Login ID: chandan
Password: chand
Now, you can enter in your application by using the login page.
For running your application you will have to copy the complete application folder in your
tomcat/webapps directory after extracting the downloaded zip file. And type the url:
http://localhost:8080/SimpleLogin/login.jsf in your browser.
Output of Simple Login Application:

If you enter wrong login id or password then the application shows the output like the
following image:
And if you enter correct login id and password then the application shows the output like as
follows:

There are some files have been used for constructing the application. These files have been
explained as follows:
Here is the code for the login.jsp file:
<%@ page contentType="text/html"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>

<f:view>
<html>
<head><title>JSF Simple Login Example</title></head>

<body>
<h:form>
<table>
<tr>
<td><h:outputText value
="Enter Login ID: " /></td>
<td><h:inputText id=
"loginname" value="#{SimpleLogin.loginname}" /></td>
</tr>
<tr>
<td><h:outputText value=
"Enter Password: " /></td>
<td><h:inputSecret id=
"password" value="#{SimpleLogin.password}" /></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><h:commandButton value=
"Login" action="#{SimpleLogin.CheckValidUser}" /></td>
</tr>
</table>
</h:form>
</body>
</html>
</f:view>

Here is the code for the resultforfail.jsp file:


Login Failed!

Here is the code for the resultforsuccess.jsp file:


Login Successful!

Here is the code for the Backing Bean SimpleLogin.java file:


package roseindia;

public class SimpleLogin{


String loginname;
String password;

public SimpleLogin(){}

public String getLoginname(){


return loginname;
}
public void setLoginname(String loginname){
this.loginname = loginname;
}

public String getPassword(){


return password;
}

public void setPassword(String password){


this.password = password;
}

public String CheckValidUser(){


if(loginname.equals("chandan") && password.equals("chand")){
System.out.println("chandan");
return "success";
}
else{
return "fail";
}
}
}

faces-config.xml file code:

<?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>SimpleLogin</managed-bean-name>
<managed-bean-class>roseindia.SimpleLogin</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<navigation-rule>
<from-view-id>/login.jsp</from-view-id>
<navigation-case>
<from-action>#{SimpleLogin.CheckValidUser}</from-
action>
<from-outcome>success</from-outcome>
<to-view-id>resultforsuccess.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-action>#{SimpleLogin.CheckValidUser}</from-
action>
<from-outcome>fail</from-outcome>
<to-view-id>resultforfail.jsp</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>

web.xml file code:


<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application
2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>

<!-- Faces Servlet -->


<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup> 1 </load-on-startup>
</servlet>

<!-- Faces Servlet Mapping -->


<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
</web-app>

Remember Me Login Application In JSF


This section gives you an application which facilitates for login. But basically this is a
different type of login application in which, you will get a two text box labeled with the label
like "User Name: " and another is the "Password: " these labels are denoting both text text
boxes in which, one is for entering user name and another is for entering password. After
entering user name and password you have to click on the "Login" button for submitting the
user login form. This login form also holds an extra component i.e. the check box component
which is for check to remember always on your system. If you check the check box
component then the user name and password will be saved until you submit the login form
after entering user name and the password without check the check box component.
You can learn by following the given example code that is given as ahead. In this example, we
are using the procedure of cookies to save user name and password. When you open the login
form again then the username and the password are seen as it is if you had checked the check
box component. You can understand the application very efficiently by seeing the code of the
example.
Here is the code of the index.jsp:
<jsp:forward
page="login.jsf" />

Here is the code of the login.jsp:


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

<f:view>
<html>
<head>
<title>Remember Me Login
Application</title>
</head>

<body>
<div align="left">
<h:form id="frm" onsubmit="return
initialize();">
<table height="250" border="1"
cellpadding="3" cellspacing="1">
<tr>
<td
valign="top"><br/><br/>
<table>

<tr>

<td><h:outputText value="User Name: "


/></td>

<td><h:inputText id="username" value


="#{RememberMeLogin.username}" /></td>

</tr>
<tr>

<td><h:outputText value="Password: "


/></td>

<td><h:inputSecret id="password"
value="#{RememberMeLogin.password}"
required="true" redisplay="true" /></td>

</tr>

<tr>

<td>&nbsp;</td>

<td><h:commandButton value="Login"
action="#{RememberMeLogin.CheckLogin}"
onclick="initialize" /></td>

</tr>

<tr>

<td>&nbsp;</td>

<td><h:selectBooleanCheckbox id=
"remember" value="#{RememberMeLogin.remember}"
onclick="return check(this);" />

<h:outputLabel for="remember">Remember
Me</h:outputLabel></td>

</tr>
</table>
</td>
</tr>
</table>
</h:form>
</div>
</body>
</html>
</f:view>

Here is the code of the RememberMeLogin.java file which is the bean class:
package roseindia;

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.faces.context.*;

public class RememberMeLogin{


boolean remember;
String username;
String password;
String remember1 = "hi";

public RememberMeLogin(){
checkCookie();
}

public void setUsername(String username){


this.username = username;
}

public String getUsername(){


if(remember == false){
username = "";
return username;
}
else{
return username;
}
}

public void setPassword(String password){


this.password = password;
}

public String getPassword(){


if(remember == false){
password = "";
return password;
}
else{
return password;
}
}

public void setRemember(boolean remember){


this.remember = remember;
}

public boolean getRemember(){


return remember;
}

public String CheckLogin(){


if(username.equals("chandan") && password.equals("chandan")){
FacesContext facesContext = FacesContext.getCurrentInstance();

// Save the userid and password in a cookie


Cookie btuser = new Cookie("btuser", username);
Cookie btpasswd = new Cookie("btpasswd",password);
if(remember == false){
remember1 = "false";
}
else{
remember1 = "true";
}
Cookie btremember = new Cookie("btremember",remember1);
btuser.setMaxAge(3600);
btpasswd.setMaxAge(3600);

((HttpServletResponse)facesContext.getExternalContext().getResponse()).
addCookie(btuser);
((HttpServletResponse)facesContext.getExternalContext().getResponse()).
addCookie(btpasswd);
((HttpServletResponse)facesContext.getExternalContext().getResponse()).
addCookie(btremember);

return "success";
}
else{
return "failure";
}
}

public void checkCookie(){


FacesContext facesContext = FacesContext.getCurrentInstance();
String cookieName = null;
Cookie cookie[] = ((HttpServletRequest)facesContext.getExternalContext().
getRequest())
.getCookies();
if(cookie != null && cookie.length > 0){
for(int i = 0; i<cookie.length; i++){
cookieName = cookie[i].getName();
if(cookieName.equals("btuser")){
username = cookie[i].getValue();
}
else if(cookieName.equals("btpasswd")){
password = cookie[i].getValue();
}
else if(cookieName.equals("btremember")){
remember1 = cookie[i].getValue();
if(remember1.equals("false")){
remember = false;
}
else if(remember1.equals("true")){
remember = true;
}
}
}
}
else
System.out.println("Cannot find any cookie");
}
}

Here is the code of the web.xml file:


<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems,
Inc.//DTD Web Application 2.3//
EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<context-param>
<param-
name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>

<!-- Faces Servlet -->


<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-
class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup> 1 </load-on-startup>
</servlet>

<!-- Faces Servlet Mapping -->


<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
</web-app>

Here is the code of the faces-config.xml file:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE faces-config PUBLIC "-//Sun Microsystems,
Inc.//DTD JavaServer Faces
Config 1.0//EN" "http://java.sun.com/dtd/web-
facesconfig_1_0.dtd">

<faces-config>
<managed-bean>
<managed-bean-
name>RememberMeLogin</managed-bean-name>
<managed-bean-
class>roseindia.RememberMeLogin</managed-bean-
class>
<managed-bean-scope>request</managed-
bean-scope>
</managed-bean>
<navigation-rule>
<from-view-id>/login.jsp</from-view-id>
<navigation-case>
<from-
action>#{RememberMeLogin.CheckLogin}</from-action>
<from-outcome>success</from-
outcome>
<to-view-id>/success.jsp</to-
view-id>
</navigation-case>
<navigation-case>
<from-
action>#{RememberMeLogin.CheckLogin}</from-action>
<from-outcome>failure</from-
outcome>
<to-view-id>/failure.jsp</to-
view-id>
</navigation-case>
</navigation-rule>
</faces-config>

Here is the output for the whole example:

JSF Validation In Login Application

This section gives you the best approach for the login application. You have learnt about the
login application without validating the application. But in this section you will learn how to
validate a form in JSF using it's tags. JSF tags give you the validation facilities for validate the
JSF form on server. Validation of the form restricts you for the wrong entries.
This section also provides you the complete source code of the application that validate your
login application. You can download the zip file and copy it inside the tomcat/webapps folder
and run it by type the following url in your browser.
URL: http://localhost:8080/LoginValidation/login.jsf.
Output of the login application with the complete validation is shown as follows:
Login ID: chandan
Password: chand
Login Form:

This is the simple login form in which you have to enter the login id and the password. This
form is validated. If you do not enter login id and password and click on the Login button then
the message will be opened like:

This image is showing you the validation error message for required value. If you enter the
login id only and click on the Login button to submit the form then the application generate a
validation error message for the required value of the password field like:
This application will generate the error message for the particular JSF form component until
you enter the login id and the password value something else.
Code of the login.jsp file that makes the login form:
<%@ page contentType="text/html"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>

<f:view>
<html>
<head><title>JSF Simple Login Example</title></head>

<body>
<h:form>
<table>
<tr>
<td><h:outputText value="Enter
Login ID: " /></td>
<td><h:inputText id="loginname"
value="#{SimpleLogin.loginname}" required="true" /><font color="#FF0000">
<h:message for="loginname"/></font></td>
</tr>
<tr>
<td><h:outputText value="Enter
Password:
" /></td>
<td><h:inputSecret id="password"
value="
#{SimpleLogin.password}" required="true" /><font color="#FF0000"><h:message
for="
password"/></font></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><h:commandButton
value="Login" action
="#{SimpleLogin.CheckValidUser}" /></td>
</tr>
</table>
</h:form>
</body>
</html>
</f:view>

Here is the code for the resultforfail.jsp file:


Login Failed!

Here is the code for the resultforsuccess.jsp file:


Login Successful!

Here is the code for the Backing Bean SimpleLogin.java file:


package roseindia;

public class SimpleLogin{


String loginname;
String password;

public SimpleLogin(){}

public String getLoginname(){


return loginname;
}

public void setLoginname(String loginname){


this.loginname = loginname;
}

public String getPassword(){


return password;
}

public void setPassword(String password){


this.password = password;
}

public String CheckValidUser(){


if(loginname.equals("chandan") && password.equals("chand")){
System.out.println("chandan");
return "success";
}
else{
return "fail";
}
}
}

faces-config.xml file code:

<?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>SimpleLogin</managed-bean-name>
<managed-bean-class>roseindia.SimpleLogin</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<navigation-rule>
<from-view-id>/login.jsp</from-view-id>
<navigation-case>
<from-action>#{SimpleLogin.CheckValidUser}</from-
action>
<from-outcome>success</from-outcome>
<to-view-id>resultforsuccess.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-action>#{SimpleLogin.CheckValidUser}</from-
action>
<from-outcome>fail</from-outcome>
<to-view-id>resultforfail.jsp</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>

web.xml file code:


<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web
Application
2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>

<!-- Faces Servlet -->


<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup> 1 </load-on-startup>
</servlet>

<!-- Faces Servlet Mapping -->


<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
</web-app>

Integrating Login And Registration Application In JSF

This tutorial explains integration of login and registration modules into one application. In this
application, if the user is valid then it enters successfully otherwise the user is asked to get
registered. The user is asked to fill some information. Some of these information are
mandatory to be filled and some are required to be filled in proper format. These fields
displays error messages if not filled properly. After successful submission of the form, all
information are displayed again to make the user confirm. If the user wants to edit some
information then it can be done by an "Modify" button. This button will bring the user to the
same form which he/she has filled before but now there is no need to fill all the information.
All the entered values will be displayed again and can be changed again.
Code for all the pages have been given below :
login.jsp :
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<f:view>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=iso-
8859-1">

<head>
<title>Login and Registration</title>
</head>

<body leftmargin="0" rightmargin="0" topmargin="40"


bottommargin="0">
<center><h:form>
<h:panelGrid width="375px" bgcolor="#e6edfd" columns="2"
border="0">
<f:facet name="header">
<h:outputText value="User Login"/>
</f:facet>

<h:outputText value="Enter Login ID:"/>


<h:inputText id="loginname"
value="#{SimpleLogin.loginname}" />

<h:outputText value="Enter Password: "/>


<h:inputSecret id="password"
value="#{SimpleLogin.password}" />

<h:outputText value=" "/>


<h:commandButton value="Login"
action="#{SimpleLogin.CheckValidUser}" />

<h:outputText value="New User?"/>


<h:commandLink value="Register Here" action="newuser" />
</h:panelGrid>
</h:form>
</center>
</body>
</html>
</f:view>

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

<f:view>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=iso-
8859-1">

<head>
<title>login success</title>
</head>

<body leftmargin="0" rightmargin="0" topmargin="40"


bottommargin="0">
<center><h:form>
<h:panelGrid width="375px" bgcolor="#e6edfd" columns="2"
border="0">
<f:facet name="header">
<h:outputText value="Welcome.....You entered
successfully"/>
</f:facet>
</h:panelGrid>
</h:form></center>
</body>
</html>
</f:view>

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

<f:view>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=iso-
8859-1">

<head>
<title>Login failed.</title>
</head>

<body leftmargin="0" rightmargin="0" topmargin="40"


bottommargin="0">
<center><h:form>
<h:panelGrid width="375px" bgcolor="#e6edfd" columns="2"
border="0">
<f:facet name="header">
<h:outputText value="Sorry...You are not registered with
us."/>
</f:facet>

<h:commandLink value="Click to Register" action="newuser" />


<h:commandLink value="Click to Go Back" action="back" />
</h:panelGrid>
</h:form>
</center>
</body>
</html>
</f:view>

result.jsp :
<%@ page contentType="text/html" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<f:view>
<html>
<head><title>Complete Person Information</title></head>
<body leftmargin="0" rightmargin="0" topmargin="40"
bottommargin="0">
<center><h:form>
<h:panelGrid width="375px" bgcolor="#e6edfd" columns="2"
border="0">
<f:facet name="header">
<h:outputText value="You have entered information :"/>
</f:facet>

<h:outputText value="Name: " />


<h:outputText value="#{persondetails.name}" />

<h:outputText value="Father's Name: " />


<h:outputText value="#{persondetails.fname}" />

<h:outputText value="Mother's Name: " />


<h:outputText value="#{persondetails.mname}" />

<h:outputText value="Current Address: " />


<h:outputText value="#{persondetails.caddress}" />

<h:outputText value="Parmanent Address: " />


<h:outputText value="#{persondetails.paddress}" />

<h:outputText value="Sex: " />


<h:outputText value="#{persondetails.sex}" />

<h:outputText value="Date Of Birth: " />


<h:outputText value="#{persondetails.dob}">
<f:convertDateTime pattern="dd-MM-yyyy"/>
</h:outputText></td>

<h:outputText value="Phone No.: " />


<h:outputText value="#{persondetails.phoneno}" />

<h:outputText value="Mobile No.: " />


<h:outputText value="#{persondetails.mobileno}" />

<h:outputText value=" " />


<h:commandButton value="Modify" action="details" />

</h:panelGrid>
</h:form></center>
</body>
</html>
</f:view>

SimpleLogin.java (JavaBean) :
Here getter method getLoginname() returns instance of type HtmlInputText because
loginname property is associated to the instance of component of this type i.e.
"HtmlInputText". In the same way setter method setLoginname() takes parameter of
HtmlInputText type because of the same reason explained above. These steps are necessary
for each component using component instance binding.
package roseindia;
public class SimpleLogin{
String loginname;
String password;

public SimpleLogin(){}

public String getLoginname(){


return loginname;
}

public void setLoginname(String loginname){


this.loginname = loginname;
}

public String getPassword(){


return password;
}

public void setPassword(String password){


this.password = password;
}

public String CheckValidUser(){


if(loginname.equals("admin") && password.equals("admin")){
System.out.println("chandan");
return "success";
}
else{
return "fail";
}
}
}

persondetails.java (JavaBean) :
package roseindia;

import java.util.Date;

public class persondetails{


String name;
String fname;
String mname;
String caddress;
String paddress;
String sex;
Date dob;
Long phoneno;
Long mobileno;

public persondetails(){}

public String getName(){


return name;
}

public void setName(String name){


this.name = name;
}

public String getFname(){


return fname;
}

public void setFname(String fname){


this.fname = fname;
}

public String getMname(){


return mname;
}

public void setMname(String mname){


this.mname = mname;
}

public String getCaddress(){


return caddress;
}

public void setCaddress(String caddress){


this.caddress = caddress;
}

public String getPaddress(){


return paddress;
}

public void setPaddress(String paddress){


this.paddress = paddress;
}

public String getSex(){


return sex;
}

public void setSex(String sex){


this.sex = sex;
}

public Date getDob(){


return dob;
}

public void setDob(Date dob){


this.dob = dob;
}

public Long getPhoneno(){


return phoneno;
}

public void setPhoneno(Long phoneno){


this.phoneno = phoneno;
}

public Long getMobileno(){


return mobileno;
}

public void setMobileno(Long mobileno){


this.mobileno = mobileno;
}

Rendered Output : This is the first page for the user.


If the user fills Login ID as "admin" and Password as "admin", then user enters
successfully. If the user is not provided ID and Password then there is a link "Register Here"
for such a new user to register itself.

This is the screen displayed when the user enters successfully.


This page appears when the user is not permitted to login successfully. There are options to go
back or register.

If the user is not registered and want to get registered then this page is filled by the user. If
user fills values in incorrect format then error messages appears to the user indicating the
errors.
If the user fills correct entry then all the information are displayed. User can modify these
information by clicking "Modify" button.
faces-config.xml :
<?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>SimpleLogin</managed-bean-name>
<managed-bean-class>roseindia.SimpleLogin</managed-bean-
class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<navigation-rule>
<from-view-id>/pages/login.jsp</from-view-id>
<navigation-case>
<from-action>#{SimpleLogin.CheckValidUser}</from-action>
<from-outcome>success</from-outcome>
<to-view-id>/pages/resultforsuccess.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-action>#{SimpleLogin.CheckValidUser}</from-action>
<from-outcome>fail</from-outcome>
<to-view-id>/pages/resultforfail.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>newuser</from-outcome>
<to-view-id>/pages/persondetails.jsp</to-view-id>
</navigation-case>

</navigation-rule>

<navigation-rule>
<from-view-id>/pages/resultforfail.jsp</from-view-id>
<navigation-case>
<from-outcome>newuser</from-outcome>
<to-view-id>/pages/persondetails.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>back</from-outcome>
<to-view-id>/pages/login.jsp</to-view-id>
</navigation-case>
</navigation-rule>

<managed-bean>
<managed-bean-name>persondetails</managed-bean-name>
<managed-bean-class>roseindia.persondetails</managed-bean-
class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<navigation-rule>
<from-view-id>/pages/persondetails.jsp</from-view-id>
<navigation-case>
<from-outcome>result</from-outcome>
<to-view-id>/pages/result.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/pages/result.jsp</from-view-id>
<navigation-case>
<from-outcome>details</from-outcome>
<to-view-id>/pages/persondetails.jsp</to-view-id>
</navigation-case>
</navigation-rule>

</faces-config>

Enabling and Disabling Button In JSF

In this tutorial enabling and disabling a button on different conditions has been explained. A
button can be disabled setting "disabled" attribute of the commandButton tag to "true". We
can set this attribute while writing the tag or by setting it according to different conditions. In this
example we have used beans to set this attribute to "true" or "false" according to the type of the
user. The first page that comes to the user is login page where the user puts login ID and
password. If ID and Password both are "admin" then the next page will be containing buttons
"Employee Area" and "Admin Area" enabled. If both are "emp" then in the next page only
one "Employee Area" button will be enabled and "Admin Area" button will be disabled. If the
ID and Password doesn't match with any of these then no button will be enabled.
Code for all the pages have been given below :
login.jsp :
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>

<f:view>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<head>
<title>Enable Disable Button</title>
</head>

<body topmargin="40"><center>
<h:form>
<table bgcolor="#e6edfd">
<tr>
<td><h:outputText value="Login ID" /></td>
<td><h:inputText id="loginname" value="#{EnableDisable.loginname}"
required="true"/></td>
<td>&nbsp;</td>
<td><h:message for="loginname" style="color:red"/></td>
</tr>
<tr>
<td><h:outputText value="Password" /></td>
<td><h:inputSecret id="password" value="#{EnableDisable.password}"
required="true"/></td>
<td>&nbsp;</td>
<td><h:message for="password" style="color:red"/></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><h:commandButton value="Login"
action="#{EnableDisable.CheckValidUser}" /></td>
</tr>
</table>
</h:form>

<center>
</body>
</html>
</f:view>

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

<f:view>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<head>
<title>Enable Disable Button</title>
</head>

<body topmargin="40">
<center>
<h:form>
<table bgcolor="#e6edfd">

<tr>
<th colspan="2"><h:outputText value="Sorry... You can't Proceed."
style="color:red;" rendered="#{EnableDisable.render3}" /></th>
</tr>
<tr>
<th colspan="2"><h:outputText value="Welcome...Go to your area."
style="color:Green;" rendered="#{EnableDisable.render4}" /></th>
</tr>
<tr>
<td><h:commandButton value="Employee Area"
disabled="#{EnableDisable.disable1}" /></td>
<td><h:commandButton value="Admin Area"
disabled="#{EnableDisable.disable2}" /></td>
</tr>
</h:form>
</center>
</body>
</html>
</f:view>

EnableDisable.java (JavaBean) :
package roseindia;

public class EnableDisable{


String loginname;
String password;
boolean disable1;
boolean disable2;
boolean render3;
boolean render4;

public EnableDisable(){
}
public String getLoginname(){
return loginname;
}
public void setLoginname(String loginname){
this.loginname = loginname;
}

public String getPassword(){


return password;
}
public void setPassword(String password){
this.password = password;
}

public boolean getDisable1(){


return disable1;
}
public void setDisable1(boolean disable1){
this.disable1 = disable1;
}

public boolean getDisable2(){


return disable2;
}
public void setDisable2(boolean disable2){
this.disable2 = disable2;
}

public boolean getRender3(){


return render3;
}
public void setRender3(boolean render3){
this.render3 = render3;
}

public boolean getRender4(){


return render4;
}
public void setRender4(boolean render4){
this.render4 = render4;
}

public String CheckValidUser(){

if(loginname.equals("admin")==true && password.equals("admin")==true){


disable1=false;
disable2=false;
render3=false;
render4=true;
}
else{
if(loginname.equals("emp")==true && password.equals("emp")==true){
disable1=false;
disable2=true;
render3=false;
render4=true;
}
else{
disable1=true;
disable2=true;
render3=true;
render4=false;
}
}

return "success";

}
}

Rendered Output : This is the first page for the user.


If the user fills Login ID as "admin" and Password as "admin":

Then user is welcome and all buttons are enabled.


If the user fills Login ID as "emp" and Password as "emp":

Then again user is welcome but "Admin Area" button is disabled.


If the user is not administrator or employee then there is a message indicating no permission to
proceed further and both buttons are disabled.

faces-config.xml :
<?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>EnableDisable</managed-bean-name>
<managed-bean-class>roseindia.EnableDisable</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<navigation-rule>
<from-view-id>/pages/login.jsp</from-view-id>
<navigation-case>
<from-action>#{EnableDisable.CheckValidUser}</from-action>
<from-outcome>success</from-outcome>
<to-view-id>/pages/EnableDisable.jsp</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
Enabling and Disabling Button In JSF

Enabling and Disabling Button In JSF


Questions In this tutorial enabling and disabling a button on different conditions has
been explained. A button can be disabled setting disabled attribute of the
 Graphs
commandButton tag to true.
Hi,I have
an
applicatio
n Google Custom
develope
Search:
d using
struts Top of Form
framewor partner-pub-0714
k.Now
the
requirem FORID:10
ent is for
displayin
g graph
in it.Can
anyone h Search
 hibernat
e code
How to Bottom of Form
store a
image in
mysql or
oracle db
using Enabling and Disabling Button In JSF
struts
&hiberna
te ?
 Dojo In this tutorial enabling and disabling a button on different
Tree conditions has been explained. A button can be disabled setting
With "disabled" attribute of the commandButton tag to "true". We
Checkbo can set this attribute while writing the tag or by setting it
x according to different conditions. In this example we have used
Hi beans to set this attribute to "true" or "false" according to the
Friends, I type of the user. The first page that comes to the user is login
have to page where the user puts login ID and password. If ID and
generate Password both are "admin" then the next page will be
a tree containing buttons "Employee Area" and "Admin Area"
structure enabled. If both are "emp" then in the next page only one
in a jsp "Employee Area" button will be enabled and "Admin Area"
along button will be disabled. If the ID and Password doesn't match
with
with any of these then no button will be enabled.
checkbox
besides Code for all the pages have been given below :
each
login.jsp :
node.
The tree <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
structure <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
is
 html <f:view>
hello ,i <html>
have <meta http-equiv="Content-Type" content="text/html; charset=iso-
some
8859-1">
problem
in my
code. <head>
there is <title>Enable Disable Button</title>
one </head>
hyper link
in my <body topmargin="40"><center>
web
<h:form>
page.
through <table bgcolor="#e6edfd">
this <tr>
hyper link <td><h:outputText value="Login ID" /></td>
i want to <td><h:inputText id="loginname"
run out value="#{EnableDisable.loginname}"
 java required="true"/></td>
swings <td>&nbsp;</td>
Hi, This is <td><h:message for="loginname" style="color:red"/></td>
my code.
</tr>
How can i
set the <tr>
image in <td><h:outputText value="Password" /></td>
the top of <td><h:inputSecret id="password"
the value="#{EnableDisable.password}"
page.Nea required="true"/></td>
r by title
<td>&nbsp;</td>
label.
Please <td><h:message for="password" style="color:red"/></td>
send the </tr>
code very <tr>
u <td>&nbsp;</td>
 com.sun <td><h:commandButton value="Login"
.facelets action="#{EnableDisable.CheckValidUser
.Facelet </tr>
ViewHan </table>
dler
</h:form>
handleR
enderEx
ception <center>
Hi All , </body>
While </html>
adding </f:view>
dynamic
menus
usting
htmlpane EnableDisable.jsp :
lmenus in <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
jsf <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
getting
fllowing
<f:view>
Exception
.Pls help <html>
me. Oct <meta http-equiv="Content-Type" content="text/html; charset=iso-
14, 2 8859-1">
 Object
oriented <head>
program <title>Enable Disable Button</title>
Write a </head>
class
called
<body topmargin="40">
RaceCar.j
ava that <center>
contains <h:form>
instance <table bgcolor="#e6edfd">
variables
horsepow <tr>
er, <th colspan="2"><h:outputText value="Sorry... You can't
weight,
Proceed."
zeroTo60
, and style="color:red;" rendered="#{EnableDisable.render3}"
milesPer /></th>
Gal. The </tr>
va <tr>
 jsp <th colspan="2"><h:outputText value="Welcome...Go to your
area."
how can i
insert style="color:Green;" rendered="#{EnableDisable.render4}"
data form /></th>
the </tr>
option <tr>
button <td><h:commandButton value="Employee Area"
into disabled="#{EnableDisable.disable1}" /></td>
database
<td><h:commandButton value="Admin Area"
 jsp disabled="#{EnableDisable.disable2}" /></td>
how can i
</tr>
insert
data form </h:form>
the </center>
option </body>
button </html>
into </f:view>
database
 jsplitpan
e
Hi, I EnableDisable.java (JavaBean) :
already package roseindia;
post the
question public class EnableDisable{
for three String loginname;
times. I String password;
need the boolean disable1;
example boolean disable2;
code for boolean render3;
jsplitpane boolean render4;
. I have
divided public EnableDisable(){
into two }
spli public String getLoginname(){
 All return loginname;
Question }
s... public void setLoginname(String loginname){
this.loginname = loginname;
Comments
}
 Null
pointer public String getPassword(){
excep return password;
 swap }
program public void setPassword(String password){
faile this.password = password;
}
 hi.........
 very public boolean getDisable1(){
good return disable1;
}
 navigato
public void setDisable1(boolean disable1){
n mobile
this.disable1 = disable1;
 All }
Comment
s... public boolean getDisable2(){
return disable2;
}
public void setDisable2(boolean disable2){
this.disable2 = disable2;
}

public boolean getRender3(){


return render3;
}
public void setRender3(boolean render3){
this.render3 = render3;
}

public boolean getRender4(){


return render4;
}
public void setRender4(boolean render4){
this.render4 = render4;
}

public String CheckValidUser(){

if(loginname.equals("admin")==true && password.equ


als("admin")==true){
disable1=false;
disable2=false;
render3=false;
render4=true;
}
else{
if(loginname.equals("emp")==true && password.equ
als("emp")==true){
disable1=false;
disable2=true;
render3=false;
render4=true;
}
else{
disable1=true;
disable2=true;
render3=true;
render4=false;
}
}

return "success";

}
}

Rendered Output : This is the first page for the user.

If the user fills Login ID as "admin" and Password as


"admin":
Then user is welcome and all buttons are enabled.

If the user fills Login ID as "emp" and Password as "emp":


Then again user is welcome but "Admin Area" button is
disabled.

If the user is not administrator or employee then there is a


message indicating no permission to proceed further and both
buttons are disabled.
faces-config.xml :
<?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>EnableDisable</managed-bean-name>
<managed-bean-class>roseindia.EnableDisable</managed-
bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<navigation-rule>
<from-view-id>/pages/login.jsp</from-view-id>
<navigation-case>
<from-action>#{EnableDisable.CheckValidUser}</from-
action>
<from-outcome>success</from-outcome>
<to-view-id>/pages/EnableDisable.jsp</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>

Retrieve Image in JSF From MySQL Table Using NetBeans IDE


This application illustrates how to retrieve image and data from MySQL table using
NetBeans IDE.
In this application we create a jsp page to display image. In this JSP page we are using
<h:graphicImage> tag to access the servlet, here we are uses servlet but as u wish u can
access a jsp page also. To create the project in the NetBeans IDE select File > click on "Create
Project" then a New Project window will be appear, select Web from Categories section and
select Web Application from Projects section. Click Next.

Put Project Name and click Next.


Choose JavaServer Faces and click Finish.
To create the jsp file right click on Web Pages select New and click JSP as below:
Here is the Source Code of data.jsp
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>

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


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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"


"http://www.w3.org/TR/html4/loose.dtd">

<f:view>
<html>
<head><h2>JSF Application</h2></head>
<body>
<center><br><br><br>
<h:dataTable id="dt1" value="#{tableBean.perInfoAll}"
var="item" bgcolor="#F1F1F1" border="10" cellpadding="5"
cellspacing="3" rows="4" width="50%">
<f:facet name="header">
<h:outputText value="This is Table Data" />
</f:facet>

<h:column>
<f:facet name="header">
<h:outputText value="Emp Name" />
</f:facet>
<h:outputText value="#{item.name}"/>

</h:column>

<h:column>
<f:facet name="header">
<h:outputText value="Image" />
</f:facet>
<h:graphicImage value="DisplayImage"/>

</h:column>

<f:facet name="footer">
<h:outputText value="The End" />
</f:facet>
</h:dataTable><br>
</center>
</body>
</html>
</f:view>

To create the package right click on Source Package and select New > Java Package..
The following window will appear then put package name and click Finish.
To create the java class right click on newly created package and select New > Java Class
Put the Class Name and click Finish.
Source Code of DisplayImage.java
package roseindia;

import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DisplayImage extends HttpServlet{

public void doGet(HttpServletRequest request, HttpServletResponse respons


e)
throws ServletException, IOException{
String connectionURL = "jdbc:mysql://localhost:3306/test";
java.sql.Connection con=null;
Statement st1;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection(connectionURL,"root","root");
st1=con.createStatement();
ResultSet rs1 = st1.executeQuery("select image from pictures where
id = '2'");
String imgLen="";
while(rs1.next()){
imgLen = rs1.getString(1);
System.out.println(imgLen.length());
int len = imgLen.length();
byte [] rb = new byte[len];
InputStream readImg = rs1.getBinaryStream(1);
int index=readImg.read(rb, 0, len);
System.out.println("index----------------"+index);
response.reset();
response.setContentType("image/jpg");
response.getOutputStream().write(rb,0,len);
response.getOutputStream().flush();

}
st1.close();
response.getOutputStream().close();
} catch (Exception e){
e.printStackTrace();
}
}
}

Create Bean class to set and get the table column as below the source code of TableBean.java
package roseindia;

import java.sql.*;
import java.util.*;
import java.io.*;

public class TableBean {


Connection con ;
Statement ps;
ResultSet rs;
private List perInfoAll = new ArrayList();

public void setPerInfoAll(List perInfoAll) {


this.perInfoAll = perInfoAll;
}

public List getPerInfoAll() {


int i = 0;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/
test","root","root");
ps = con.createStatement();
rs = ps.executeQuery("select name from emp");
while(rs.next()){
perInfoAll.add(i,new tableData(rs.getString("name")));
i++;
}
} catch (Exception e) {
System.out.println("Error Data : " + e.getMessage());
}
return perInfoAll;
}

public class tableData {


private String name;

public tableData(String name) {


this.name = name;
}

public void setName(String name) {


this.name = name;
}

public String getName() {


System.out.println("Name: "+name);
return name;
}
}
}

Servlet Mapping in web.xml


<servlet>
<servlet-
name>DisplayImage</servlet-
name>
<servlet-
class>roseindia.DisplayImage</
servlet-class>
</servlet>
<servlet-mapping>
<servlet-
name>DisplayImage</servlet-
name>
<url-
pattern>/DisplayImage</url-
pattern>
</servlet-mapping>

Source Code of faces-config.xml


<?xml version='1.0' encoding='UTF-8'?>

<!-- =========== FULL CONFIGURATION FILE ================================== -


->

<faces-config version="1.2"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://j
ava.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">

<managed-bean>
<managed-bean-name>tableBean</managed-bean-name>
<managed-bean-class>roseindia.TableBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>

</faces-config>

The Output shown on the Browser as below:

Você também pode gostar