JSF
JSF
JSF
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.
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:
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.
In the above code fragment we have imported two JSF tag libraries with the help of taglib
directive. JSF Core Tag Library contains set of JSF core tags while JSF Html Tags Library
contains set of html tags. Prefix is used to use tags defined in tag library. Here we are using
conventional names f and h for Core & Html tags respectively. We have the choice to choose
any name for the prefixes.
• JSF Html Tags:
These tags represent html components like text fields, buttons, form.
Html tags can be divided into following categories:
Some examples have been given below to understand how to use these tags and its
attributes:
<h: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.
These tags allows you to take advantages of features of JSF framework, like validation,
conversion , event handling. Core library is stepchild of Html library. i.e. core library
supports the html library. Core tag library also contains tags for views and sub-views ,
loading resource bundle, adding arbitrary text to a page. Some examples of JSF core
tags are:
Some examples have been given below to understand how to use these tags:
<f:view locale="en">
<h:outputText value="label" />
</f:view>
f: view tag is used to create top level view and is a container for all JSF component
tags on a page. Where locale attribute provides several options for presenting
localized views of your application. Here "en" represents English and if we give velue
"fr" to locale attribute then french view will be displayed. So this attribute is useful for
internationalization purpose.
<f:view>
<h1>head</h1>
<p>view</p>
<f:subview id="sub_id">
<c:import url="second.jsp" />
</f:subview>
</f:view>
Here f:subview tag is like container for the JSF components contained in an included
JSP page (second.jsp).
<h:inputText id="txt_id"
value="txt_value">
<f:validator validatorId="Txt_Validator" />
</h:inputText>
The Validator tag registers a Validator on the component associated with the
enclosing tag. In validatorId field, we give the value of one of the validator-id element
of a validator in your Faces configuration file.
In JSF Core Tag Library there are 18 core tags .
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)
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>.
<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>
Connection con ;
Statement ps;
ResultSet rs;
private List perInfoAll = new ArrayList();
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;
}
String uname;
String firstName;
String 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>
<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>
<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 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 {
<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.
Code Description :
<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>
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.
<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>
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 :
<f:view>
<html>
<head><title>jsf h:inputText example</title></head>
<body>
<h:inputText />
</body>
</html>
</f:view>
Rendered Output :
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 :
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 :
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.
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.
<body>
Hello, chandan !
</body>
</html>
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.
<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:
<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:
<body>
<b>This is the output text.</b>
</body>
</html>
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 :
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.
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.
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 :
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}"
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 :
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 :
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 :
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">
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 :
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.*;
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 :
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> </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 :
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> </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 :
<table>
<tr><td><font color="#FF0000"></font></td>
<td> </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>
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 :
<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>
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 :
</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 :
<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 :
<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.*;
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 :
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 :
<br><br>
PASSWORD(minimum 6 characters)<br>
<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 :
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> </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(){}
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.
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.*;
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 :
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 :
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 :
//<![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>
<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 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.
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 :
<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 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.
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 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 :
<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:
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
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.
<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:".
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.
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:
<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> 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>
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.
<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>
<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>
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:
<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>
<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>
<web-app>
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>
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>
<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>
<web-app>
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>
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:
<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");
}
qText.setAttribute('autocomplete','off');
var x = findPosX(qText);
var y = findPosY(qText);
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();
}
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();
}
}
if(!isIE){
Document.prototype.loadXML = function (s) {
var doc2 = (new DOMParser()).parseFromString(s, "text/xml");
while (this.hasChildNodes())
this.removeChild(this.lastChild);
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 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();
public SelectedTitleRecord(){
setTitleDetails();
}
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;
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>
<h:outputText value="User Name." /><br>
<h:inputText value="#{Bean.userName}"/><br><br>
<h:outputText value="Phone No." /><br>
<h:inputText value="#{Bean.phoneNo}" /><br><br>
<h:outputText value="Company Name" /><br>
<h:inputText value="#{Bean.company}" /><br><br>
<h:outputText value="Thought of the day" /><br>
<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".
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> </td>
<td><h:commandButton value=
"Login" action="#{SimpleLogin.CheckValidUser}" /></td>
</tr>
</table>
</h:form>
</body>
</html>
</f:view>
public SimpleLogin(){}
<?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-app>
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>
<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>
</tr>
<tr>
<td><h:inputSecret id="password"
value="#{RememberMeLogin.password}"
required="true" redisplay="true" /></td>
</tr>
<tr>
<td> </td>
<td><h:commandButton value="Login"
action="#{RememberMeLogin.CheckLogin}"
onclick="initialize" /></td>
</tr>
<tr>
<td> </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 RememberMeLogin(){
checkCookie();
}
((HttpServletResponse)facesContext.getExternalContext().getResponse()).
addCookie(btuser);
((HttpServletResponse)facesContext.getExternalContext().getResponse()).
addCookie(btpasswd);
((HttpServletResponse)facesContext.getExternalContext().getResponse()).
addCookie(btremember);
return "success";
}
else{
return "failure";
}
}
<web-app>
<context-param>
<param-
name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>
<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>
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> </td>
<td><h:commandButton
value="Login" action
="#{SimpleLogin.CheckValidUser}" /></td>
</tr>
</table>
</h:form>
</body>
</html>
</f:view>
public SimpleLogin(){}
<?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-app>
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>
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>
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>
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>
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: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(){}
persondetails.java (JavaBean) :
package roseindia;
import java.util.Date;
public persondetails(){}
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>
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> </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> </td>
<td><h:message for="password" style="color:red"/></td>
</tr>
<tr>
<td> </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 EnableDisable(){
}
public String getLoginname(){
return loginname;
}
public void setLoginname(String loginname){
this.loginname = loginname;
}
return "success";
}
}
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
return "success";
}
}
<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>
<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.*;
}
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.*;
<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>