You are on page 1of 53

UNIT – II

What is JavaServer Pages?


JavaServer Pages (JSP) is a technology for developing Webpages that supports
dynamic content. This helps developers insert java code in HTML pages by making use
of special JSP tags, most of which start with <% and end with %>.

A JavaServer Pages component is a type of Java servlet that is designed to fulfill the
role of a user interface for a Java web application. Web developers write JSPs as text
files that combine HTML or XHTML code, XML elements, and embedded JSP actions
and commands.

Using JSP, you can collect input from users through Webpage forms, present records
from a database or another source, and create Webpages dynamically.

JSP tags can be used for a variety of purposes, such as retrieving information from a
database or registering user preferences, accessing JavaBeans components, passing
control between pages, and sharing information between requests, pages etc.

Why Use JSP?


JavaServer Pages often serve the same purpose as programs implemented using
the Common Gateway Interface (CGI). But JSP offers several advantages in
comparison with the CGI.

 Performance is significantly better because JSP allows embedding Dynamic


Elements in HTML Pages itself instead of having separate CGI files.

 JSP are always compiled before they are processed by the server unlike CGI/Perl
which requires the server to load an interpreter and the target script each time
the page is requested.

 JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP
also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI,
EJB, JAXP, etc.

 JSP pages can be used in combination with servlets that handle the business
logic, the model supported by Java servlet template engines.
Finally, JSP is an integral part of Java EE, a complete platform for enterprise class
applications. This means that JSP can play a part in the simplest applications to the
most complex and demanding.

Advantages of JSP
Following table lists out the other advantages of using JSP over other technologies −

vs. Active Server Pages (ASP)


The advantages of JSP are twofold. First, the dynamic part is written in Java, not
Visual Basic or other MS specific language, so it is more powerful and easier to use.
Second, it is portable to other operating systems and non-Microsoft Web servers.

vs. Pure Servlets


It is more convenient to write (and to modify!) regular HTML than to have plenty of
println statements that generate the HTML.

vs. Server-Side Includes (SSI)


SSI is really only intended for simple inclusions, not for "real" programs that use form
data, make database connections, and the like.

vs. JavaScript
JavaScript can generate HTML dynamically on the client but can hardly interact with
the web server to perform complex tasks like database access and image processing
etc.

vs. Static HTML


Regular HTML, of course, cannot contain dynamic information.

JSP – Architecture (Framework Roles)


Model 1 and Model 2 (MVC) Architecture
Before developing the web applications, we need to have idea about design models. There are
two types of programming models (design models)

1. Model 1 Architecture
2. Model 2 (MVC) Architecture

Model 1 Architecture
Servlet and JSP are the main technologies to develop the web applications.
Servlet was considered superior to CGI. Servlet technology doesn't create process, rather it
creates thread to handle request. The advantage of creating thread over process is that it
doesn't allocate separate memory area. Thus many subsequent requests can be easily handled
by servlet.

Problem in Servlet technology Servlet needs to recompile if any designing code is modified.


It doesn't provide separation of concern. Presentation and Business logic are mixed up.

JSP overcomes almost all the problems of Servlet. It provides better separation of concern,
now presentation and business logic can be easily separated. You don't need to redeploy the
application if JSP page is modified. JSP provides support to develop web application using
JavaBean, custom tags and JSTL so that we can put the business logic separate from our JSP
that will be easier to test and debug.

As you can see in the above figure, there is picture which show the flow of the model1
architecture.

1. Browser sends request for the JSP page


2. JSP accesses Java Bean and invokes business logic
3. Java Bean connects to the database and get/save data
4. Response is sent to the browser which is generated by JSP

Advantage of Model 1 Architecture


o Easy and Quick to develop web application

Disadvantage of Model 1 Architecture


o Navigation control is decentralized since every page contains the logic to determine
the next page. If JSP page name is changed that is referred by other pages, we need to
change it in all the pages that leads to the maintenance problem.
o Time consuming You need to spend more time to develop custom tags in JSP. So that
we don't need to use scriptlet tag.
o Hard to extend It is better for small applications but not for large applications.
Model 2 (MVC) Architecture
Model 2 is based on the MVC (Model View Controller) design pattern. The MVC design pattern
consists of three modules model, view and controller.

Model The model represents the state (data) and business logic of the application.

View The view module is responsible to display data i.e. it represents the presentation.

Controller The controller module acts as an interface between view and model. It intercepts all
the requests i.e. receives input and commands to Model / View to change accordingly.

Advantage of Model 2 (MVC) Architecture


o Navigation control is centralized Now only controller contains the logic to determine
the next page.
o Easy to maintain
o Easy to extend
o Easy to test
o Better separation of concerns

Disadvantage of Model 2 (MVC) Architecture


o We need to write the controller code self. If we change the controller code, we need to
recompile the class and redeploy the application.

Solution of Model 2 Architecture: Configurable MVC Components


It uses the declarative approach for defining view components, request mapping etc. It
resolves the problem of Model 2 architecture. The Struts framework provides the configurable
MVC support. In struts 2, we define all the action classes and view components in struts.xml
file.

MVC Architecture in JSP with Example

What is MVC?
MVC is an architecture that separates business logic, presentation and data.
In MVC,

 M stands for Model


 V stands for View
 C stands for controller.

MVC is a systematic way to use the application where the flow starts from the
view layer, where the request is raised and processed in controller layer and
sent to model layer to insert data and get back the success or failure
message.

Model Layer:

 This is the data layer which consists of the business logic of the system.
 It consists of all the data of the application
 It also represents the state of the application.
 It consists of classes which have the connection to the database.
 The controller connects with model and fetches the data and sends to
the view layer.
 The model connects with the database as well and stores the data into a
database which is connected to it.

View Layer:

 This is a presentation layer.


 It consists of HTML, JSP, etc. into it.
 It normally presents the UI of the application.
 It is used to display the data which is fetched from the controller which in
turn fetching data from model layer classes.
 This view layer shows the data on UI of the application.

Controller Layer:
 It acts as an interface between View and Model.
 It intercepts all the requests which are coming from the view layer.
 It receives the requests from the view layer and processes the requests
and does the necessary validation for the request.
 This requests is further sent to model layer for data processing, and
once the request is processed, it sends back to the controller with
required information and displayed accordingly by the view.

The diagram is represented below:

Example of MVC architecture


In this example, we are going to show how to use MVC architecture in JSP.

 We are taking the example of a form with two variables "email" and
"password" which is our view layer.
 Once the user enters email, and password and clicks on submit then the
action is passed in mvc_servlet where email and password are passed.
 This mvc_servlet is controller layer. Here in mvc_servlet the request is
sent to the bean object which act as model layer.
 The email and password values are set into the bean and stored for
further purpose.
 From the bean, the value is fetched and shown in the view layer.

What is JSF?
JavaServer Faces (JSF) is a MVC web framework that simplifies the construction of
User Interfaces (UI) for server-based applications using reusable UI components in a
page. JSF provides a facility to connect UI widgets with data sources and to server-
side event handlers. The JSF specification defines a set of standard UI components
and provides an Application Programming Interface (API) for developing components.
JSF enables the reuse and extension of the existing standard UI components.

Benefits
JSF reduces the effort in creating and maintaining applications, which will run on a
Java application server and will render application UI on to a target client. JSF
facilitates Web application development by −

 Providing reusable UI components

 Making easy data transfer between UI components

 Managing UI state across multiple server requests

 Enabling implementation of custom components

 Wiring client-side event to server-side application code

To create a simple JSF application, we'll use maven-archetype-webapp plugin. In the


following example, we'll create a maven-based web application project in C:\JSF
folder.

Create Project
Let's open command console, go the C:\ > JSF directory and execute the
following mvn command.

C:\JSF>mvn archetype:create
-DgroupId = com.tutorialspoint.test
-DartifactId = helloworld
-DarchetypeArtifactId = maven-archetype-webapp

Maven will start processing and will create the complete java web application project
structure.

[INFO] Scanning for projects...


[INFO] Searching repository for plugin with prefix: 'archetype'.
[INFO] -------------------------------------------------------------
[INFO] Building Maven Default Project
[INFO] task-segment: [archetype:create] (aggregator-style)
[INFO] -------------------------------------------------------------
[INFO] [archetype:create {execution: default-cli}]
[INFO] Defaulting package to group ID: com.tutorialspoint.test
[INFO] artifact org.apache.maven.archetypes:maven-archetype-webapp:
checking for updates from central
[INFO] -------------------------------------------------------------
[INFO] Using following parameters for creating project
from Old (1.x) Archetype: maven-archetype-webapp:RELEASE
[INFO] -------------------------------------------------------------
[INFO] Parameter: groupId, Value: com.tutorialspoint.test
[INFO] Parameter: packageName, Value: com.tutorialspoint.test
[INFO] Parameter: package, Value: com.tutorialspoint.test
[INFO] Parameter: artifactId, Value: helloworld
[INFO] Parameter: basedir, Value: C:\JSF
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir:
C:\JSF\helloworld
[INFO] -------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] -------------------------------------------------------------
[INFO] Total time: 7 seconds
[INFO] Finished at: Mon Nov 05 16:05:04 IST 2012
[INFO] Final Memory: 12M/84M
[INFO] -------------------------------------------------------------

Now go to C:/JSF directory. You'll see a Java web application project created, named
helloworld (as specified in artifactId). Maven uses a standard directory layout as
shown in the following screenshot.

Using the above example, we can understand the following key concepts.

S.No Folder Structure & Description

1 helloworld

Contains src folder and pom.xml

2 src/main/wepapp

Contains WEB-INF folder and index.jsp page

3 src/main/resources
It contains images/properties files (In the above example, we need to
create this structure manually)

Add JSF Capability to Project


Add the following JSF dependencies.

<dependencies>

<dependency>

<groupId>com.sun.faces</groupId>

<artifactId>jsf-api</artifactId>

<version>2.1.7</version>

</dependency>

<dependency>

<groupId>com.sun.faces</groupId>

<artifactId>jsf-impl</artifactId>

<version>2.1.7</version>

</dependency>

</dependencies>

Complete POM.xml

<project xmlns = "http://maven.apache.org/POM/4.0.0"

xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0

http://maven.apache.org/maven-v4_0_0.xsd">

<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint.test</groupId>

<artifactId>helloworld</artifactId>

<packaging>war</packaging>

<version>1.0-SNAPSHOT</version>

<name>helloworld Maven Webapp</name>

<url>http://maven.apache.org</url>

<dependencies>

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>3.8.1</version>

<scope>test</scope>

</dependency>

<dependency>

<groupId>com.sun.faces</groupId>

<artifactId>jsf-api</artifactId>

<version>2.1.7</version>

</dependency>

<dependency>

<groupId>com.sun.faces</groupId>

<artifactId>jsf-impl</artifactId>

<version>2.1.7</version>

</dependency>
</dependencies>

<build>

<finalName>helloworld</finalName>

<plugins>

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-compiler-plugin</artifactId>

<version>2.3.1</version>

<configuration>

<source>1.6</source>

<target>1.6</target>

</configuration>

</plugin>

</plugins>

</build>

</project>

Prepare Eclipse Project


Let's open the command console. Go the C:\ > JSF > helloworld directory and
execute the following mvn command.

C:\JSF\helloworld>mvn eclipse:eclipse -Dwtpversion = 2.0

Maven will start processing, create the eclipse ready project, and will add wtp
capability.

Downloading: http://repo.maven.apache.org/org/apache/maven/plugins/
maven-compiler-plugin/2.3.1/maven-compiler-plugin-2.3.1.pom
5K downloaded (maven-compiler-plugin-2.3.1.pom)
Downloading: http://repo.maven.apache.org/org/apache/maven/plugins/
maven-compiler-plugin/2.3.1/maven-compiler-plugin-2.3.1.jar
29K downloaded (maven-compiler-plugin-2.3.1.jar)
[INFO] Searching repository for plugin with prefix: 'eclipse'.
[INFO] ------------------------------------------------------------
[INFO] Building helloworld Maven Webapp
[INFO] task-segment: [eclipse:eclipse]
[INFO] ------------------------------------------------------------
[INFO] Preparing eclipse:eclipse
[INFO] No goals needed for project - skipping
[INFO] [eclipse:eclipse {execution: default-cli}]
[INFO] Adding support for WTP version 2.0.
[INFO] Using Eclipse Workspace: null
[INFO] Adding default classpath container: org.eclipse.jdt.
launching.JRE_CONTAINER
Downloading: http://repo.maven.apache.org/
com/sun/faces/jsf-api/2.1.7/jsf-api-2.1.7.pom
12K downloaded (jsf-api-2.1.7.pom)
Downloading: http://repo.maven.apache.org/
com/sun/faces/jsf-impl/2.1.7/jsf-impl-2.1.7.pom
10K downloaded (jsf-impl-2.1.7.pom)
Downloading: http://repo.maven.apache.org/
com/sun/faces/jsf-api/2.1.7/jsf-api-2.1.7.jar
619K downloaded (jsf-api-2.1.7.jar)
Downloading: http://repo.maven.apache.org/
com/sun/faces/jsf-impl/2.1.7/jsf-impl-2.1.7.jar
1916K downloaded (jsf-impl-2.1.7.jar)
[INFO] Wrote settings to C:\JSF\helloworld\.settings\
org.eclipse.jdt.core.prefs
[INFO] Wrote Eclipse project for "helloworld" to C:\JSF\helloworld.
[INFO]
[INFO] -----------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] -----------------------------------------------------------
[INFO] Total time: 6 minutes 7 seconds
[INFO] Finished at: Mon Nov 05 16:16:25 IST 2012
[INFO] Final Memory: 10M/89M
[INFO] -----------------------------------------------------------

Import Project in Eclipse


Following are the steps −

 Import project in eclipse using Import wizard.

 Go to File → Import... → Existing project into workspace.

 Select root directory to helloworld.

 Keep Copy projects into workspace to be checked.

 Click Finish button.


 Eclipse will import and copy the project in its workspace C:\ → Projects → Data
→ WorkSpace.

Configure Faces Servlet in web.xml


Locate web.xml in webapp → WEB-INF folder and update it as shown below.

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

<web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"

xmlns = "http://java.sun.com/xml/ns/javaee"

xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

id = "WebApp_ID" version="2.5">

<welcome-file-list>

<welcome-file>faces/home.xhtml</welcome-file>

</welcome-file-list>

<!--

FacesServlet is main servlet responsible to handle all request.

It acts as central controller.

This servlet initializes the JSF components before the JSP is displayed.

-->
<servlet>

<servlet-name>Faces Servlet</servlet-name>

<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>Faces Servlet</servlet-name>

<url-pattern>/faces/*</url-pattern>

</servlet-mapping>

<servlet-mapping>

<servlet-name>Faces Servlet</servlet-name>

<url-pattern>*.jsf</url-pattern>

</servlet-mapping>

<servlet-mapping>

<servlet-name>Faces Servlet</servlet-name>

<url-pattern>*.faces</url-pattern>

</servlet-mapping>

<servlet-mapping>

<servlet-name>Faces Servlet</servlet-name>

<url-pattern>*.xhtml</url-pattern>

</servlet-mapping>
</web-app>

Create a Managed Bean


Create a package structure under src → main → java as com → tutorialspoint →
test. Create HelloWorld.java class in this package. Update the code
of HelloWorld.java as shown below.

package com.tutorialspoint.test;

import javax.faces.bean.ManagedBean;

@ManagedBean(name = "helloWorld", eager = true)

public class HelloWorld {

public HelloWorld() {

System.out.println("HelloWorld started!");

public String getMessage() {

return "Hello World!";

Create a JSF page


Create a page home.xhtml under webapp folder. Update the code of home.xhtml as
shown below.

<!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>JSF Tutorial!</title>

</head>

<body>

#{helloWorld.getMessage()}

</body>

</html>

Build the Project


Following are the steps.

 Select helloworld project in eclipse

 Use Run As wizard

 Select Run As → Maven package

 Maven will start building the project and will create helloworld.war under C:\ →
Projects → Data → WorkSpace → helloworld → target folder.

[INFO] Scanning for projects...


[INFO] -----------------------------------------------------
[INFO] Building helloworld Maven Webapp
[INFO]
[INFO] Id: com.tutorialspoint.test:helloworld:war:1.0-SNAPSHOT
[INFO] task-segment: [package]
[INFO] -----------------------------------------------------
[INFO] [resources:resources]
[INFO] Using default encoding to copy filtered resources.
[INFO] [compiler:compile]
[INFO] Nothing to compile - all classes are up to date
[INFO] [resources:testResources]
[INFO] Using default encoding to copy filtered resources.
[INFO] [compiler:testCompile]
[INFO] No sources to compile
[INFO] [surefire:test]
[INFO] Surefire report directory:
C:\Projects\Data\WorkSpace\helloworld\target\surefire-reports

-------------------------------------------------------
T E S T S
-------------------------------------------------------
There are no tests to run.

Results :

Tests run: 0, Failures: 0, Errors: 0, Skipped: 0

[INFO] [war:war]
[INFO] Packaging webapp
[INFO] Assembling webapp[helloworld] in
[C:\Projects\Data\WorkSpace\helloworld\target\helloworld]
[INFO] Processing war project
[INFO] Webapp assembled in[150 msecs]
[INFO] Building war:
C:\Projects\Data\WorkSpace\helloworld\target\helloworld.war
[INFO] ------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------
[INFO] Total time: 3 seconds
[INFO] Finished at: Mon Nov 05 16:34:46 IST 2012
[INFO] Final Memory: 2M/15M
[INFO] ------------------------------------------------

Deploy WAR file


Following are the steps.

 Stop the tomcat server.

 Copy the helloworld.war file to tomcat installation directory → webapps


folder.

 Start the tomcat server.

 Look inside webapps directory, there should be a folder helloworld got created.

 Now helloworld.war is successfully deployed in Tomcat Webserver root.

Run Application
Enter a url in web browser: http://localhost:8080/helloworld/home.jsfto launch
the application.

Server name (localhost) and port (8080) may vary as per your tomcat configuration.
JSF User Interface Component Model
JavaServer Faces provides rich set of components library to define the architecture of
application.

It includes the following:

Rich set of classes for specifying the state and behavior of user interface components.

o A rendering model that defines how to render the components in various ways.
o A conversion model that defines how to register data converters onto a component.
o An event and listener model that defines how to handle component events.
o A validation model that defines how to register validators onto a component.

JSF User Interface Components


JavaServer Faces HTML tag library represents HTML form components and other basic HTML
elements, which are used to display or accept data from the user. A JSF form send this data to
the server after submitting the form.

The following table contains the user interface components.

Tag Functions Rendered As Appearance

h:inputText It allows a user to An HTML <input A field


input a string. type="text"> element

h:outputText It displays a line of Plain text Plain text


text.

h:form It represents an An HTML <form> No appearance


input form. element

h:commandButt It submits a form An HTML <input A button


on to the application. type=value> element for
which the type value can
be "submit", "reset", or
"image"

h:inputSecret It allows a user to An HTML <input A field that displays a


input a string type="password"> row of characters
without the actual element instead of the actual
string appearing in string entered.
the field.

h:inputTextarea It allows a user to An HTML <textarea> A multirow field


enter a multiline element
string.

h:commandLink It links to another An HTML <a href> A link


page or location on element
a page.

h:inputSecret It allows a user to An HTML <input A field that displays a


input a string type="password"> row of characters
without the actual element instead of the actual
string appearing in string entered.
the field.

h:inputHidden It allows a page An HTML <input No appearance


author to include a type="hidden"> element
hidden variable in
a page.

h:inputFile It allows a user to An HTML <input A field with a Browse


upload a file. type="file"> element button

h:graphicImage It displays an An HTML <img> element An image


image.

h:dataTable It represents a An HTML <table> A table that can be


data wrapper. element updated dynamically.

h:message It displays a An HTML <span> tag if A text string


localized message. styles are used

h:messages It displays localized A set of HTML <span> A text string


messages. tags if styles are used

h:outputFormat It displays a Plain text Plain text


formatted
message.

h:outputLabel It displays a nested An HTML <label> Plain text


component as a element
label for a specified
input field.

h:outputLink It links to another An HTML <a> element A link


page or location on
a page without
generating an
action event.

h:panelGrid It displays a table. An HTML <table> A table


element with <tr> and
<td> elements
h:panelGroup It groups a set of A HTML <div> or <span> A row in a table
components under element
one parent.

h:selectBoolean It allows a user to An HTML <input A check box


Checkbox change the value type="checkbox">
of a Boolean element
choice.

h:selectManyCh It displays a set of A set of HTML <input> A group of check


eckbox check boxes from elements of type boxes
which the user can checkbox
select multiple
values.

h:selectManyLis It allows a user to An HTML <select> A box


tbox select multiple element
items from a set of
items all displayed
at once.

h:selectManyMe It allows a user to An HTML <select> A menu


nu select multiple element
items from a set of
items.

h:selectOneList It allows a user to An HTML <select> A box


box select one item element
from a set of items
all displayed at
once.

h:selectOneMen It allows a user to An HTML <select> A menu


u select one item element
from a set of
items.

h:selectOneRadi It allows a user to An HTML <input A group of options


o select one item type="radio"> element
from a set of
items.

h:column It represents a A column of data in an A column in a table


column of data in a HTML table
data component.

JSF UI Components Example


JSF provides inbuilt components to create web pages. Here, we are creating a user registration
for with the help of JSF components. Follow the following steps to create the form.

1) Creating a User Registration Form


// index.xhtml

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/
xhtml1/DTD/xhtml1-transitional.dtd">  
2. <html xmlns="http://www.w3.org/1999/xhtml"  
3. xmlns:h="http://xmlns.jcp.org/jsf/html"  
4. xmlns:f="http://xmlns.jcp.org/jsf/core">  
5. <h:head>  
6. <title>User Registration Form</title>  
7. </h:head>  
8. <h:body>  
9. <h:form id="form">  
10. <table>  
11. <tr>  
12. <td><h:outputLabel for="username">User Name</h:outputLabel></td>  
13. <td><h:inputText id="name-id" value="#{user.name}"/></td>  
14. </tr>  
15. <tr>  
16. <td><h:outputLabel for="email">Your Email</h:outputLabel></td>  
17. <td><h:inputText id="email-id" value="#{user.email}"/></td>  
18. </tr>  
19. <tr>  
20. <td><h:outputLabel for="password">Password</h:outputLabel></td>  
21. <td><h:inputSecret id="password-id" value="#{user.password}"/></td>  
22. </tr>  
23.   
24. <tr>  
25. <td><h:outputLabel for="gender">Gender</h:outputLabel></td>  
26. <td><h:selectOneRadio value="#{user.gender}">  
27. <f:selectItem itemValue="Male" itemLabel="Male" />  
28. <f:selectItem itemValue="Female" itemLabel="Female" />  
29. </h:selectOneRadio></td>  
30. </tr>  
31. <tr><td><h:outputLabel for="address">Address</h:outputLabel></td>  
32. <td><h:inputTextarea value="#{user.address}" cols="50" rows="5"/></td></tr> 
 
33. </table>  
34. <h:commandButton value="Submit" action="response.xhtml"></
h:commandButton>  
35. </h:form>  
36. </h:body>  
37. </html>  

2) Creating a Managed Bean


// User.java

1. import javax.faces.bean.ManagedBean;  
2. import javax.faces.bean.RequestScoped;  
3. @ManagedBean  
4. @RequestScoped  
5. public class User{  
6. String name;  
7. String email;  
8. String password;  
9. String gender;  
10. String address;  
11. public String getName() {  
12. return name;  
13. }  
14. public void setName(String name) {  
15. this.name = name;  
16. }  
17. public String getEmail() {  
18. return email;  
19. }  
20.   
21. public void setEmail(String email) {  
22. this.email = email;  
23. }  
24. public String getPassword() {  
25. return password;  
26. }  
27. public void setPassword(String password) {  
28. this.password = password;  
29. }  
30. public String getGender() {  
31. return gender;  
32. }  
33. public void setGender(String gender) {  
34. this.gender = gender;  
35. }  
36. public String getAddress() {  
37. return address;  
38. }  
39. public void setAddress(String address) {  
40. this.address = address;  
41. }      
42. }  

3) Creating an Output Page


// response.xhtml

1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/
xhtml1/DTD/xhtml1-transitional.dtd">  
2. <html xmlns="http://www.w3.org/1999/xhtml"  
3. xmlns:h="http://xmlns.jcp.org/jsf/html"  
4. xmlns:f="http://xmlns.jcp.org/jsf/core">  
5. <h:head>  
6. <title>User Details</title>  
7. </h:head>  
8. <h:body>  
9. <h2><h:outputText value="Hello #{user.name}"/></h2>  
10. <h4><h:outputText value="You have Registered with us Successfully, Your Details ar
e The Following."/></h4>  
11. <table>  
12. <tr>  
13. <td><b>Email: </b></td>  
14. <td><h:outputText value="#{user.email}"/><br/></td>  
15. </tr>  
16. <tr>  
17. <td><b>Password:</b></td>  
18. <td><h:outputText value="#{user.password}"/><br/></td>  
19. </tr>  
20. <tr>  
21. <td><b>Gender:</b></td>  
22. <td><h:outputText value="#{user.gender}"/><br/></td>  
23. </tr>  
24. <tr>  
25. <td><b>Address: </b></td>  
26. <td><h:outputText value="#{user.address}"/></td>  
27. </tr>  
28. </table>  
29. </h:body>  
30. </html>  

4) Run the Application


Output:
User Registration Form (index page).

After submitting form, JSF renders response.xhtml file as a result web page.

// response page

JSF - Page Navigation


Navigation rules are those rules provided by JSF Framework that describes which view
is to be shown when a button or a link is clicked.

Navigation rules can be defined in JSF configuration file named faces-config.xml. They
can be defined in managed beans.
Navigation rules can contain conditions based on which the resulted view can be
shown. JSF 2.0 provides implicit navigation as well in which there is no need to define
navigation rules as such.

Implicit Navigation
JSF 2.0 provides auto view page resolver mechanism named implicit navigation.
In this case, you only need to put view name in action attribute and JSF will search the
correct view page automatically in the deployed application.

Auto Navigation in JSF Page


Set view name in action attribute of any JSF UI Component.

<h:form>

<h3>Using JSF outcome</h3>

<h:commandButton action = "page2" value = "Page2" />

</h:form>

Here, when Page2 button is clicked, JSF will resolve the view name, page2as


page2.xhtml extension, and find the corresponding view file page2.xhtmlin the
current directory.
Auto Navigation in Managed Bean
Define a method in managed bean to return a view name.

@ManagedBean(name = "navigationController", eager = true)

@RequestScoped

public class NavigationController implements Serializable {

public String moveToPage1() {

return "page1";

Get view name in action attribute of any JSF UI Component using managed bean.

<h:form>

<h3> Using Managed Bean</h3>

<h:commandButton action = "#{navigationController.moveToPage1}"

value = "Page1" /glt;

</h:form>

Here, when Page1 button is clicked, JSF will resolve the view name, page1as


page1.xhtml extension, and find the corresponding view file page1.xhtmlin the
current directory.
Conditional Navigation
Using managed bean, we can very easily control the navigation. Look at the following
code in a managed bean.

@ManagedBean(name = "navigationController", eager = true)

@RequestScoped

public class NavigationController implements Serializable {

//this managed property will read value from request parameter pageId

@ManagedProperty(value = "#{param.pageId}")

private String pageId;

//condional navigation based on pageId


//if pageId is 1 show page1.xhtml,

//if pageId is 2 show page2.xhtml

//else show home.xhtml

public String showPage() {

if(pageId == null) {

return "home";

if(pageId.equals("1")) {

return "page1";

}else if(pageId.equals("2")) {

return "page2";

}else {

return "home";

Pass pageId as a request parameter in JSF UI Component.

<h:form>

<h:commandLink action = "#{navigationController.showPage}" value = "Page1">

<f:param name = "pageId" value = "1" />

</h:commandLink>

<h:commandLink action = "#{navigationController.showPage}" value = "Page2">

<f:param name = "pageId" value = "2" />

</h:commandLink>
<h:commandLink action = "#{navigationController.showPage}" value = "Home">

<f:param name = "pageId" value = "3" />

</h:commandLink>

</h:form>

Here, when "Page1" button is clicked.

 JSF will create a request with parameter pageId = 1

 Then JSF will pass this parameter to managed property pageId of


navigationController

 Now navigationController.showPage() is called which will return view as page1


after checking the pageId

 JSF will resolve the view name, page1 as page1.xhtml extension

 Find the corresponding view file page1.xhtml in the current directory

Resolving Navigation Based on from-action


JSF provides navigation resolution option even if managed bean different methods
returns the same view name.
Look at the following code in a managed bean.

public String processPage1() {

return "page";

public String processPage2() {

return "page";

To resolve views, define the following navigation rules in faces-config.xml

<navigation-rule>

<from-view-id>home.xhtml</from-view-id>

<navigation-case>

<from-action>#{navigationController.processPage1}</from-action>

<from-outcome>page</from-outcome>

<to-view-id>page1.jsf</to-view-id>

</navigation-case>

<navigation-case>

<from-action>#{navigationController.processPage2}</from-action>
<from-outcome>page</from-outcome>

<to-view-id>page2.jsf</to-view-id>

</navigation-case>

</navigation-rule>

Here, when Page1 button is clicked −

 navigationController.processPage1() is called which will return view as page

 JSF will resolve the view name, page1 as view name is page and from-
action in faces-config is navigationController.processPage1

 Find the corresponding view file page1.xhtml in the current directory

Forward vs Redirect
JSF by default performs a server page forward while navigating to another page and
the URL of the application does not change.

To enable the page redirection, append faces-redirect=true at the end of the view


name.
<h:form>

<h3>Forward</h3>

<h:commandButton action = "page1" value = "Page1" />

<h3>Redirect</h3>

<h:commandButton action = "page1?faces-redirect = true" value = "Page1" />

</h:form>

Here, when Page1 button under Forward is clicked, you will get the following result.

Here when Page1 button under Redirect is clicked, you will get the following result.
Example Application
Let us create a test JSF application to test all of the above navigation examples.

Step Description

Create a project with a name helloworld under a package


1
com.tutorialspoint.test as explained in the JSF - Create Applicationchapter.

Create NavigationController.java under a package com.tutorialspoint.testas
2
explained below.

Create faces-config.xml under a WEB-INF folder and updated its contents


3
as explained below.

4 Update web.xml under a WEB-INF folder as explained below.

Create page1.xhtml and page2.xhtml and modify home.xhtml under
5
a webapp folder as explained below.

Compile and run the application to make sure business logic is working as
6
per the requirements.

Finally, build the application in the form of war file and deploy it in Apache
7
Tomcat Webserver.
Launch your web application using appropriate URL as explained below in
8
the last step.

NavigationController.java

package com.tutorialspoint.test;

import java.io.Serializable;

import javax.faces.bean.ManagedBean;

import javax.faces.bean.ManagedProperty;

import javax.faces.bean.RequestScoped;

@ManagedBean(name = "navigationController", eager = true)

@RequestScoped

public class NavigationController implements Serializable {

private static final long serialVersionUID = 1L;

@ManagedProperty(value = "#{param.pageId}")

private String pageId;

public String moveToPage1() {

return "page1";

public String moveToPage2() {

return "page2";

}
public String moveToHomePage() {

return "home";

public String processPage1() {

return "page";

public String processPage2() {

return "page";

public String showPage() {

if(pageId == null) {

return "home";

if(pageId.equals("1")) {

return "page1";

}else if(pageId.equals("2")) {

return "page2";

}else {

return "home";

}
public String getPageId() {

return pageId;

public void setPageId(String pageId) {

this.pageId = pageId;

faces-config.xml

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

<faces-config

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://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"

version = "2.0">

<navigation-rule>

<from-view-id>home.xhtml</from-view-id>

<navigation-case>

<from-action>#{navigationController.processPage1}</from-action>

<from-outcome>page</from-outcome>

<to-view-id>page1.jsf</to-view-id>

</navigation-case>

<navigation-case>
<from-action>#{navigationController.processPage2}</from-action>

<from-outcome>page</from-outcome>

<to-view-id>page2.jsf</to-view-id>

</navigation-case>

</navigation-rule>

</faces-config>

web.xml

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

<display-name>Archetype Created Web Application</display-name>

<context-param>

<param-name>javax.faces.PROJECT_STAGE</param-name>

<param-value>Development</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>

<servlet>

<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>Faces Servlet</servlet-name>

<url-pattern>*.jsf</url-pattern>

</servlet-mapping>

</web-app>

page1.xhtml

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

<!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:h = "http://java.sun.com/jsf/html">

<h:body>

<h2>This is Page1</h2>

<h:form>

<h:commandButton action = "home?faces-redirect = true"

value = "Back To Home Page" />

</h:form>

</h:body>

</html>

page2.xhtml

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

<!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:h = "http://java.sun.com/jsf/html">

<h:body>

<h2>This is Page2</h2>

<h:form>

<h:commandButton action = "home?faces-redirect = true"

value = "Back To Home Page" />

</h:form>

</h:body>

</html>

home.xhtml

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

<!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:f = "http://java.sun.com/jsf/core"

xmlns:h = "http://java.sun.com/jsf/html">

<h:body>

<h2>Implicit Navigation</h2>

<hr />

<h:form>
<h3>Using Managed Bean</h3>

<h:commandButton action = "#{navigationController.moveToPage1}"

value = "Page1" />

<h3>Using JSF outcome</h3>

<h:commandButton action = "page2" value = "Page2" />

</h:form>

<br/>

<h2>Conditional Navigation</h2>

<hr />

<h:form>

<h:commandLink action = "#{navigationController.showPage}"

value="Page1">

<f:param name = "pageId" value = "1" />

</h:commandLink>

     

<h:commandLink action = "#{navigationController.showPage}"

value="Page2">

<f:param name = "pageId" value = "2" />

</h:commandLink>

     

<h:commandLink action = "#{navigationController.showPage}"

value = "Home">

<f:param name = "pageId" value = "3" />


</h:commandLink>

</h:form>

<br/>

<h2>"From Action" Navigation</h2>

<hr />

<h:form>

<h:commandLink action = "#{navigationController.processPage1}"

value = "Page1" />

     

<h:commandLink action = "#{navigationController.processPage2}"

value = "Page2" />

     

</h:form>

<br/>

<h2>Forward vs Redirection Navigation</h2>

<hr />

<h:form>

<h3>Forward</h3>

<h:commandButton action = "page1" value = "Page1" />

<h3>Redirect</h3>

<h:commandButton action = "page1?faces-redirect = true"

value = "Page1" />

</h:form>
</h:body>

</html>

Once you are ready with all the changes done, let us compile and run the application
as we did in JSF - Create Application chapter. If everything is fine with your
application, this will produce the following result.

JSF - Life Cycle


JSF application life cycle consists of six phases which are as follows −

 Restore view phase


 Apply request values phase; process events

 Process validations phase; process events

 Update model values phase; process events

 Invoke application phase; process events

 Render response phase

The six phases show the order in which JSF processes a form. The list shows the
phases in their likely order of execution with event processing at each phase.

Phase 1: Restore view


JSF begins the restore view phase as soon as a link or a button is clicked and JSF
receives a request.

During this phase, JSF builds the view, wires event handlers and validators to UI
components and saves the view in the FacesContext instance. The FacesContext
instance will now contain all the information required to process a request.

Phase 2: Apply request values


After the component tree is created/restored, each component in the component tree
uses the decode method to extract its new value from the request parameters.
Component stores this value. If the conversion fails, an error message is generated
and queued on FacesContext. This message will be displayed during the render
response phase, along with any validation errors.

If any decode methods event listeners called renderResponse on the current


FacesContext instance, the JSF moves to the render response phase.

Phase 3: Process validation


During this phase, JSF processes all validators registered on the component tree. It
examines the component attribute rules for the validation and compares these rules to
the local value stored for the component.

If the local value is invalid, JSF adds an error message to the FacesContext instance,
and the life cycle advances to the render response phase and displays the same page
again with the error message.

Phase 4: Update model values


After the JSF checks that the data is valid, it walks over the component tree and sets
the corresponding server-side object properties to the components' local values. JSF
will update the bean properties corresponding to the input component's value
attribute.

If any updateModels methods called renderResponse on the current FacesContext


instance, JSF moves to the render response phase.

Phase 5: Invoke application


During this phase, JSF handles any application-level events, such as submitting a
form/linking to another page.

Phase 6: Render response


During this phase, JSF asks container/application server to render the page if the
application is using JSP pages. For initial request, the components represented on the
page will be added to the component tree as JSP container executes the page. If this
is not an initial request, the component tree is already built so components need not
be added again. In either case, the components will render themselves as the JSP
container/Application server traverses the tags in the page.

After the content of the view is rendered, the response state is saved so that
subsequent requests can access it and it is available to the restore view phase.

Using JavaServer Faces Technology in JSP Pages


The page author’s responsibility is to design the pages of a JavaServer Faces application. This includes laying out
the components on the page and wiring them to backing beans, validators, converters, and other server-side
objects associated with the page. This chapter uses the Duke’s Bookstore application and the Coffee Break
application (see Chapter 36, The Coffee Break Application) to describe how page authors use the JavaServer
Faces tags to perform the following tasks:
 Lay out standard UI components on a page
 Reference localized messages
 Register converters, validators, and listeners on components
 Bind components and their values to server-side objects
 Reference backing bean methods that perform navigation processing, handle events, and perform validation

This chapter also describes how to include custom objects created by application developers and component
writers on a JSP page.

The Example JavaServer Faces Application


The JavaServer Faces technology chapters of this tutorial primarily use a rewritten version of the Duke’s
Bookstore example to illustrate the basic concepts of JavaServer Faces technology. This version of the Duke’s
Bookstore example includes several JavaServer Faces technology features:

 The JavaServer Faces implementation provides FacesServlet, whose instances accept incoming requests
and pass them to the implementation for processing. Therefore, the application does not need to include a
servlet (such as the Dispatcher servlet) that processes request parameters and dispatches to application
logic, as do the other versions of Duke’s Bookstore.
 A custom image map component that allows you to select the locale for the application.
 Navigation configured in a centralized application configuration resource file. This eliminates the need to
calculate URLs, as other versions of the Duke’s Bookstore application must do.
 Backing beans associated with the pages. These beans hold the component data and perform other
processing associated with the components. This processing includes handling the event generated when a
user clicks a button or a hyperlink.
 The table that displays the books from the database and the shopping cart are rendered with
the dataTable tag, which is used to dynamically render data in a table. The dataTable tag on tut-
install/javaeetutorial5/examples/web/bookstore6/web/bookshowcart.jsp also includes input
components.
 The table that displays the books from the database uses a c:forEach JSTL tag, demonstrating that you can
easily use JavaServer Faces component tags with JSTL tags.
 A custom validator and a custom converter are registered on the credit card field of
the bookcashier.jsp page.
 A value-change listener is registered on the Name field of bookcashier.jsp. This listener saves the name in
a parameter so that tut-
install/javaeetutorial5/examples/web/bookstore6/web/bookreceipt.jsp can access it.

This version of Duke’s Bookstore includes the same pages listed in Table 5-1. It also includes the tut-
install/javaeetutorial5/examples/web/bookstore6/web/chooselocale.jsp page, which displays the
custom image map that allows you to select the locale of the application. This page is displayed first and advances
directly to the bookstore.jsp page after the locale is selected.

The packages of the Duke’s Bookstore application are:

 backing: Includes the backing bean classes


 components: Includes the custom UI component classes
 converters: Includes the custom converter class
 listeners: Includes the event handler and event listener classes
 model: Includes a model bean class
 renderers: Includes the custom renderers
 resources: Includes custom error messages for the custom converter and validator
 taglib: Includes custom tag handler classes
 util: Includes a message factory class
 validators: Includes a custom validator class
Chapter 12, Developing with JavaServer Faces Technology describes how to program backing beans, custom
converters and validators, and event listeners. Chapter 13, Creating Custom UI Components describes how to
program event handlers, custom components, renderers, and tag handlers.

The source code for the application is located in the tut-


install/javaeetutorial5/examples/web/bookstore6/ directory.

To deploy and run the application using NetBeans IDE, follow these steps:

1. Perform all the operations described in Accessing Databases from Web Applications.
2. In NetBeans 5.5, select File→Open Project.
3. In the Open Project dialog, navigate to:

tut-install/javaeetutorial5/examples/web/

4. Select the bookstore6 folder.
5. Select the Open as Main Project check box and the Open Required Projects check box.
6. Click Open Project.
7. In the Projects tab, right-click the bookstore6 project, and select Undeploy and Deploy.
8. To run the application, open the bookstore URL http://localhost:8080/bookstore6.

To deploy and run the application using Ant, follow these steps:

1. In a terminal window, go to tut-install/javaeetutorial5/examples/web/bookstore6/.


2. Type ant. This target will spawn any necessary compilations, copy files to the tut-
install/javaeetutorial5/examples/web/bookstore6/build/ directory, and create a WAR file and copy
it to the tut-install/javaeetutorial5/examples/web/bookstore6/dist/ directory.
3. Start the Application Server.
4. Perform all the operations described in Creating a Data Source in the Application Server.
5. To deploy the example, type ant deploy. The deploy target outputs a URL for running the application.
Ignore this URL, and instead use the one shown in the next step.
6. To run the application, open the bookstore URL http://localhost:8080/bookstore6/.

To learn how to configure the example, refer to the web.xml file, which includes the following elements:

 A display-name element that specifies the name that tools use to identify the application.
 A context-param element that specifies that the javax.faces.STATE_SAVING_METHOD parameter has a
value of client, meaning that state is saved on the client.
 A listener element that identifies the ContextListener class used to create and remove the database
access.
 A servlet element that identifies the FacesServlet instance.
 A servlet-mapping element that maps FacesServlet to a URL pattern.
 Nested inside a jsp-config element is a jsp-property-group element, which sets the properties for the
group of pages included in this version of Duke’s Bookstore. See Setting Properties for Groups of JSP
Pages for more information.

To run the example, open the URL http://localhost:8080/bookstore6 in a browser.

Setting Up a Page
A typical JavaServer Faces page includes the following elements:

 A set of tag library declarations that declare the two JavaServer Faces tag libraries
 A view tag
 A form tag
This section tells you how to add these elements to your pages and briefly describes the subview tag for including
JavaServer Faces pages inside other pages.

To use the JavaServer Faces UI components in your JSP page, you need to give the page access to the two
standard tag libraries: the JavaServer Faces HTML render kit tag library and the JavaServer Faces core tag
library. The JavaServer Faces standard HTML render kit tag library defines tags that represent common HTML
user interface components. The JavaServer Faces core tag library defines tags that perform core actions and are
independent of a particular render kit.

Using these tag libraries is similar to using any other custom tag library. This chapter assumes that you are familiar
with the basics of using custom tags in JSP pages (see Using Custom Tags).

As is the case with any tag library, each JavaServer Faces tag library must have a TLD that describes it.
The html_basic TLD describes the JavaServer Faces standard HTML render kit tag library. The jsf_core TLD
describes the JavaServer Faces core tag library.

Refer to the TLD documentation at http://download.oracle.com/javaee/5/javaserverfaces/1.2/docs/tlddocs/ for a


complete list of the JavaServer Faces tags and their attributes.

To use any of the JavaServer Faces tags, you need to include these taglib directives at the top of each page
containing the tags defined by these tag libraries:

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


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

The uri attribute value uniquely identifies the TLD. The prefix attribute value is used to distinguish tags
belonging to the tag library. You can use other prefixes rather than the h or f prefixes. However, you must use the
prefix you have chosen when including the tag in the page. For example, the form tag must be referenced in the
page using the h prefix because the preceding tag library directive uses the h prefix to distinguish the tags defined
in html_basic.tld:

<h:form ...>

A page containing JavaServer Faces tags is represented by a tree of components. At the root of the tree is
the UIViewRoot component. The view tag represents this component on the page. Therefore, all component tags
on the page must be enclosed in the view tag, which is defined in the jsf_core TLD:

<f:view>
... other JavaServer Faces tags, possibly mixed with other
content ...
</f:view>

You can enclose other content, including HTML and other JSP tags, within the view tag, but all JavaServer Faces
tags must be enclosed within the view tag.

The view tag has four optional attributes:

 A locale attribute. If this attribute is present, its value overrides the Locale stored in


the UIViewRoot component. This value is specified as a String and must be of this form:

:language:[{-,_}:country:[{-,_}:variant]

The language, country, and variant parts of the expression are as specified in java.util.Locale.


 A renderKitId attribute. A page author uses this attribute to refer to the ID of the render kit used to render
the page, therefore allowing the use of custom render kits. If this attribute is not specified, the default HTML
render kit is assumed. The process of creating custom render kits is outside the scope of this tutorial.
 A beforePhase attribute. This attribute references a method that takes a PhaseEvent object and
returns void, causing the referenced method to be called before each phase (except restore view) of the life
cycle begins.
 An afterPhase attribute. This attribute references a method that takes a PhaseEvent object and returns
void, causing the referenced method to be called after each phase (except restore view) in the life cycle ends.

An advanced developer might implement the methods referenced by beforePhase and afterPhase to perform


such functions as initialize or release resources on a per-page basis. This feature is outside of the scope of this
tutorial.

The form tag is nested inside of the view tag. As its name suggests, the form tag represents a form, which is
submitted when a button or hyperlink on the page is clicked. For the data of other components on the page to be
submitted with the form, the tags representing the components must be nested inside the form tag. See Adding a
Form Component for more details on using the form tag.

If you want to include a page containing JavaServer Faces tags within another JSP page that includes JavaServer
Faces tags, you must enclose the entire nested page in a subview tag. You can add the subview tag on the
parent page and nest a jsp:include inside it to include the page:

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

You can also include the subview tag inside the nested page, but it must enclose all the JavaServer Faces tags
on the nested page.

The subview tag has two optional attributes: binding and rendered. The binding attribute binds to a


component that implements NamingContainer. One potential use case of binding a subview component to a
bean is if you want to dynamically add components to the subview in the backing bean.

The rendered attribute can be set to true or false, indicating whether or not the components nested in
the subview tag should be rendered.

In summary, a typical JSP page that uses JavaServer Faces tags will look somewhat like this:

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


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

<f:view>
<h:form>
other JavaServer Faces tags and core tags,
including one or more button or hyperlink components for
submitting the form
</h:form>
</f:view>

The sections Using the Core Tags and Adding UI Components to a Page Using the HTML Component
Tags describe how to use the core tags from the JavaServer Faces core tag library and the component tags from
the JavaServer Faces standard HTML render kit tag library.

Using the Core Tags


The tags included in the JavaServer Faces core tag library are used to perform core actions that are independent
of a particular render kit. These tags are listed in Table 11-1.
Table 11-1 The jsf_core Tags
Tag Categories Tags Functions

Event-handling actionListener Registers an action listener on a parent component


tags
phaseListener Registers a PhaseListener instance on
a UIViewRoot component
setPropertyActionListener Registers a special action listener whose sole purpose is to
push a value into a backing bean when a form is submitted
valueChangeListener Registers a value-change listener on a parent component

Attribute attribute Adds configurable attributes to a parent component


configuration tag

Data conversion converter Registers an arbitrary converter on the parent component


tags
convertDateTime Registers a DateTime converter instance on the parent
component
convertNumber Registers a Number converter instance on the parent
component

Facet tag facet Signifies a nested component that has a special relationship
to its enclosing tag

Localization tag loadBundle Specifies a ResourceBundle that is exposed as a Map

Parameter param Substitutes parameters into a MessageFormat instance and


substitution tag adds query string name-value pairs to a URL

Tags for selectItem Represents one item in a list of items in


representing a UISelectOne or UISelectManycomponent
items in a list
selectItems Represents a set of items in
a UISelectOne or UISelectMany component

Container tag subview Contains all JavaServer Faces tags in a page that is included
in another JSP page containing JavaServer Faces tags

Validator tags validateDoubleRange Registers a DoubleRangeValidator on a component


validateLength Registers a LengthValidator on a component
validateLongRange Registers a LongRangeValidator on a component
validator Registers a custom validator on a component

Output tag verbatim Generates a UIOutput component that gets its content from
the body of this tag

Container for view Encloses all JavaServer Faces tags on the page
form tags

These tags are used in conjunction with component tags and are therefore explained in other sections of this
tutorial. Table 11-2 lists the sections that explain how to use specific jsf_core tags.

Table 11-2 Where the jsf_core Tags Are Explained


Tags Where Explained
Event-handling tags Registering Listeners on Components

Data conversion tags Using the Standard Converters


facet Using Data-Bound Table Components and Laying Out Components with
the UIPanel Component
loadBundle Rendering Components for Selecting Multiple Values
param Displaying a Formatted Message with the outputFormat Tag

selectItem and selectItems The UISelectItem, UISelectItems, and UISelectItemGroup Components

subview Setting Up a Page


verbatim Rendering a Hyperlink with the outputLink Tag
view Setting Up a Page

Validator tags Using the Standard Validators and Creating a Custom Validator

JSF - Convertor Tags


JSF provides inbuilt convertors to convert its UI component's data to object used in a
managed bean and vice versa. For example, these tags can convert a text into date
object and can validate the format of input as well.

For these tags, you need to use the following namespaces of URI in html node.

<html

xmlns = "http://www.w3.org/1999/xhtml"

xmlns:f = "http://java.sun.com/jsf/core">

Following are important Convertor Tags in JSF 2.0 −

S.No Tag & Description

f:convertNumber
1
Converts a String into a Number of desired format

f:convertDateTime
2
Converts a String into a Date of desired format
Custom Convertor
3
Creating a custom convertor

JSF - Validator Tags


JSF provides inbuilt validators to validate its UI components. These tags can validate
the length of the field, the type of input which can be a custom object.

For these tags you need to use the following namespaces of URI in html node.

<html
xmlns = "http://www.w3.org/1999/xhtml"
xmlns:f = "http://java.sun.com/jsf/core">

Following are important Validator Tags in JSF 2.0−

S.No Tag & Description

f:validateLength
1
Validates the length of a string

f:validateLongRange
2
Validates the range of a numeric value

f:validateDoubleRange
3
Validates the range of a float value

f:validateRegex
4
Validates JSF component with a given regular expression

Custom Validator
5
Creates a custom validator

You might also like