Brief description  about Online courses   join in Online courses

Developing Web Application with JSF

Diksha  Basu
Diksha Basu
Java Programmers

JavaServer Faces is a new framework for building Web applications using Java.

JSF is a one of standard Java framework for building Web applications. It helps and simplifies the development of web pages. It is a component based approach like VB in Windows.  Following tutorial explains how you can create and deploy a sample JSF application. It also explains you how you can add various components to a jsp page.


  • MyEclipse 6 IDE or Eclipse 3
  • Tomcat 6 or above
  • Java 1.5

Here we create and execute a simple web application with JavaServer Faces 1.2. This is most suited for those who develop a JSF application for the first time. This may look terribly descriptive for those who are already familiar with creating and running JSF projects. I am not going to the details of JSF technology here. There are lots of other sites and books that does it. Here my intention is to help you create your 'first' JSF project running on our PC.

Just like any other Java Web application, we need Eclipse (I am using version 3.5.1) with Apache Tomcat 6.0 set up in our system.
First thing first, let's start with creating a new Dynamic Web project.
Select File -> New -> Project
Select  Dynamic Web project in the Wizard, as shown below, and click Next.
Give Project name BasicJSFProject. Click New button to select the 'Target Runtime'. In the popup window(screen shot is not provided) select the  type of runtime environment as ApacheTomacat v6.0. Specify the tomcat installation directory and click Finish. Select the dynamic web module version as 2.5. In the configuration section, select the JavaServer Faces Project v1.2. Click next.
Click next.    
Check Generate web.xml deployment descriptor and Click next.
Click download library
Select JSF 1.2 (SUN RI). Click next. Accept the terms of license. Click Finish.
Select JSF 1.2(SUN RI) and click Finish.
Your BasicJSFProject has been created. Note that the web.xml file has been updated with the Faces Servlet and servlet-mapping, a stub JSF application configuration file (faces-config.xml) has been created, and the build path has been updated with the implementation jars.
Now we are all set to start our coding. But before that we should have a clear idea about what we are going to build. It's a simple web page which receives 4 input from the user and displays the result on the same page on successful submission.
Now, we will create a backing bean file. It's a simple Java bean with four attribute(name,age,email,dob) and setter/getter methods for the four attributes. The bean simply captures the name,age,email,dob entered by a user after the user clicks the Submit button. This way the bean provides a bridge between the JSP page and the application logic.
Create a new Java class.
enter the package as, com.user.details and the Name of the class as UserDetails. Click the Finish button.
package com.user.details;
import java.util.Date;

public class UserDetails {
  private String name;
  private Integer age=null;
  private String email;
  private Date dob;
Add attributes and generate getter and setters
Select all four attributes to create getters ans setters and Click OK.
package com.user.details;
import java.util.Date;

public class UserDetails {
  private String name;
  private Integer age=null;
  private String email;
  private Date dob;
  private boolean submitted = false
  public boolean isSubmitted() {
    return submitted;

  public String submitUserDetails() {
    submitted =true;
    return "submitted";

  public Date getDob() {
    return dob;

  public void setDob(Date dob) {
    this.dob = dob;

  public String getName() {
    return name;

  public void setName(String name) { = name;
  public Integer getAge() {
    return age;

  public void setAge(Integer age) {
    this.age = age;
  public String getEmail() {
    return email;

  public void setEmail(String email) { = email;

Create a JSF JSP Page:
Create a folder "pages" in WebContent folder of BasicJSFProject application.
Type folder name "pages" and click Finish.
Now the pages folder is created in WebContent folder of our application.
Create a new page UserDetailsForm.jsp in the WebContent/pages folder of the application.
Type the file name UserDetailsForm.jsp and click Next
In the Select Templates page of the wizard , select the New Java Server Faces(JSF) page(html) template. Click Finish. The page will be opened in the Web Page Editor.
Configuring Managed Bean in faces-config.xml
We will configure the managed bean before editing the UserDetailsForm.jsp.
In the Project Explorer, expand the node, BasicJSFProject->WebContent. Double-click on faces-config.xml . This will launch the Faces Configuration editor. Select the ManagedBean tab.

Click on the Add button. This will launch the New Managed Bean wizard.
Select the option, Using an existing Java class. In the next wizard panel, search for the class we created Click Ok button.
Select the scope as request and click Finish.
We have registered class as a managed bean. JSF-managed beans are standard JavaBeans that are used to hold user-entered data in JSF applications. Save the Faces Configuration editor.Select source tab. Your final faces-config.xml file
The managed bean name is given as userDetails. Now we can use the bean named userDetails in our UserDetailsForm page. For example to bind a JSF user interface component (UI Component eg:inputText) to one of the properties(eg:name) of userDetails, we use the expression #{} as a value argument to a JSF UI Component.
Here is an example of binding the name property of the bean to a JSF inputText (UIInput) UI Component.
<h:inputText value="#{}"/>

So now upon any form submissions the value entered into the input text field will be applied to the property of Java Bean. Please note that the field name in the JSP file must exactly match the attribute name in the bean.

Now we will start building the UserDetailsForm.jsp

In order to use JavaServer Faces components in JSP pages, you need to give your pages access to the two standard tag libraries, the core tag library and the HTML component tag library using taglib declarations:The former provides a few general tags and some other tags that let you register validators and event listeners to UI components. The latter contains JSP tags that render HTML UI components such as buttons, text fields, checkboxes, lists, etc. The UserDetailsForm.jsp page uses many of these tags to build its form. The standard prefixes of these two tag libraries are 'f 'and 'h', and they are declared at the beginning of UserDetailsForm.jsp
For your JSF application to work, it needs a set of .jar files containing the JSF reference implementation and other libraries. Copy the following .jar files to the WEB-INF/lib directory.

  • commons-beanutils-1.7.0.jar
  • commons-codec-1.3.jar
  • commons-collections-3.2.jar
  • commons-digester-1.8.jar
  • commons-logging-1.1.1.jar
  • jstl-1.2.jar
  • standard.jar
If the jars that contain the tag libraries are present on the classpath, then content assist for the tags should be available. Add the JSF tag, <h:inputText >With the cursor inside the brackets, hit Ctrl+spacebar . You should see a pop-up with a list of all attributes.
Add the value argument (value="#{}" )in <h:inputText > tag . With the cursor inside the curley brackets, hit Ctrl+spacebar . You should see a pop-up with a list of all the implicit objects plus the managed bean defined above. Select the managed bean, userDetails. Have you added OutputText and inputText for (name, age, email ,and dob) and commandButton in the your page?
In the UserDetailsForm.jsp page we need to assosiate the Submit button with userDetails bean. For that you have to mention a method submitUserDetails in the Use the action attribute to associate the button with a JavaBean’s method.  An action method must be a public method with no parameters that returns a String. The returned string represents the logical outcome of the action (eg. "submitted","success", "failure", etc.) and is used by the JavaServer Faces for page navigation. Defining page navigation involves determining which page to go to after the user clicks a button or a hyperlink. We will discuss page navigation in the next session.
In our example when user enter the details and click submit button, a message is displayed on the same page
Add the following code to the UserDetails class.

private boolean submitted = false;

public boolean isSubmitted(){
return submitted;
public String submitUserDetails() {
submitted =true;
return "submitted";
Since we are not implementing page navigation here the return value "submitted" has no significance in this example.

Add the following code to UserDetailsForm.jsp
<h:panelGrid rendered="#{userDetails.submitted != false}" >
<h:outputLabel value="User Details submitted successfully"></h:outputLabel>
When user clicks submit button the boolean variable "submitted" will be set to true. If the rendered attribute in the panelGrid evaluates to true ,the component should be rendered. A boolean false suppress rendering.
JSF Conversion and Validation

As we all know the values submitted from a web page to the server over http will always be of type string. But the backing bean variable can be of any java data type.for eg in our example the variable dob is of type Date. There should be a mechanism to convert strings into appropriate java type. JSF convertors does the  conversion and ensure that the data is of appropriate type before setting to backing bean. Here is an example of conversions we use in our application.
  • string value is convertible to a java.util.Date
As for validation, it ensures data contains the expected content. A validation example is shown:

  • java.util.Date is MM/DD/YYYY format
How to use standard conversion and validation features in JSF

We want to make sure that no empty name,age,email and dob is submitted. To do that, we will use the required attribute for the inputText tag in UserDetailsForm.jsp. Setting this attribute to true will ensure that no empty value is submitted.

But I don't want my message to sound so general, like `Validation Error: Value is required`.
I want my error message to be customized for each field, like:
Please enter your Name
Please enter your age
Please enter your email
Please enter your dob

The most-improved feature of JavaServer Faces 1.2 technology is the ability to add custom messages to a JavaServer Faces application. The improvements in this area include

  • New requiredMessage, converterMessage, and validatorMessage attributes for input components
These attributes accept literal values as well as value expressions, as do most JavaServer Faces tag attributes. Therefore, you can use a value expression to reference a message contained in a resource bundle. We will discuss about resource bundle later.

The value of an input component's requiredMessage attribute overrides the default message for the required validation failure. The value of an input component's converterMessage attribute overrides the default message of the converter registered on the input component. Likewise, the value of an input component's validatorMessage attribute overrides the default message of the validator registered on the input component.

Adding a custom message

Adding Code to Check for

  • Empty Input for a Name.
  • Reasonable Length of Input for a Name

<h:inputText id="name" value="#{}"

            requiredMessage="Please enter your Name"
            validatorMessage="Please enter more than 3 characters for name">
           <f:validateLength minimum="3"/>
Adding validations for age
In example app the user's age can be any valid integer. Because it doesn't make sense to allow an age of, say, -2, you'll probably want to add some validation to the field.
<h:inputText id="age" value="#{userDetails.age}" required="true"
         requiredMessage="Please enter your age"
         validatorMessage="Please enter correct age ">
        <f:validateLongRange minimum="0" maximum="150"/>
Once you have the age field sorted out, you need to check whether user has entered value in the email field . You could code this as follows:
<h:inputText id="email" value="#{}" required="true"
         requiredMessage="Please enter your email">
Validating an Email Address we will discuss in another section.

Once you have done with email field,you need to check whether user has entered value in the dob field and the value entered is in MM/DD/YYYY pattern. Here's the code:
<h:inputText id="dob" value="#{userDetails.dob}"
         requiredMessage="Please enter your Date Of Birth"
         converterMessage="Please enter the date in MM/DD/YYYY">
         <f:convertDateTime type="date" pattern="MM/dd/yyyy"/>
Displaying error message.

Last thing that we need to do is to add some kind of error message warning to the user. A message tag can be used to display error messages on a page when data conversion or validation fails after the user submits the form. The error message displays wherever you place the message tag on the page.

I have put the message tag on the begining of the page and set the color for the messages using the style attribute.
<h:messages style="color: blue"/>
The error message will be displayed in blue colour.
Now we have completed with our folowing UserDetailsForm.jsp.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="f"  uri=""%>
<%@ taglib prefix="h"  uri=""%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<h:outputText value="USER DETAILS FORM"> </h:outputText>
         <h:messages style="color: blue"/>
 <h:form id="userDetailsForm">
 <h:panelGrid  columns="2">
 <h:outputText value="Name :"></h:outputText>
 <h:inputText id="name"  value="#{}"
  requiredMessage="Please enter your Name"
  validatorMessage="Please enter more than 3 characters for name">
  <f:validateLength minimum="3"/>
   <h:outputText value="Age"></h:outputText>
  <h:inputText id="age" value="#{userDetails.age}" required="true" requiredMessage="Please enter your age"
  validatorMessage="Please enter correct age ">
   <f:validateLength maximum="3"/>
    <h:outputText value="Email"></h:outputText>
  <h:inputText id="email" value="#{}" required="true"
  requiredMessage="Please enter your email"></h:inputText>
   <h:outputText value="Date Of Birth"></h:outputText>
  <h:inputText id="dob" value="#{userDetails.dob}"
  requiredMessage="Please enter your Date Of Birth"
  converterMessage="Please enter the date in MM/DD/YYYY">
  <f:convertDateTime type="date" pattern="MM/dd/yyyy"/>
  <h:commandButton value="Submit" action="#{userDetails.submitUserDetails}"></h:commandButton>
  <h:panelGrid rendered="#{userDetails.submitted != false}" >
  <h:outputLabel value="User Details submitted successfully"></h:outputLabel>

Create index.jsp:
  1. In project Explorer select WebContent. From its context menu select New/File; the New File wizard appears.
  2. For File name enter index.jsp. click Finish; the JSP Editor opens.
  3. Enter the following code in the JSP Editor, save the file and close the editor.
         <jsp:forward page="/pages/UserDetailsForm.jsf">

The index.jsp page is the entry point of our application.

Run your webapplication

To run your web application, right click on BasicJSFProject, click- >run as -> run on server.

Select the server type ,Apache Tomacat v6.0 Server.Click Fininsh.

Open a web browser and type the url :

JavaServer Faces is a new framework for building Web applications using Java. In this tutorial we have gone through the following features of JavaServer Faces :
  • Standard user interface components like input fields, buttons, and links
  • User input validation
  • Easy error handling.
  • Java bean managemen
Write your comment now
Reader's comments(1)
1: fdgdfh
Posted by:hgdh - 27 Apr, 2018