JSF Beginner's Guide - 2

<< Previous        Next >>

Developing an Application with JSF 1.2 - Part 2

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 (screen shot not shown), 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. ManagedBean tab is shown below.

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 UserDetails.java. Click Ok button.

Select the scope as request and click Finish.

We have registered UserDetails.java 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 should look like this:

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 #{userDetails.name} 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="#{userdetails.name}"/>

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? Does your code looks similar to one shown below?

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 UserDetails.java. 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 as shown below.

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 in the next section.

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="#{userDetails.name}"
            requiredMessage="Please enter your Name"
            validatorMessage="Please enter more than 3 characters for name">
           <f:validateLength minimum="3"/>

Adding validations for age

In our 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="#{userDetails.email}" 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 UserDetailsForm.jsp.The page look like


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"></jsp:forward>

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 : http://localhost:8080/BasicJSFProject/

As a conclusion:

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 management

See More Topics:

How page navigation works in JSF?
How to use resource bundle in JSF?
How to implement Internationalization and Localization in JSF?
How event handling works in JSF?
JSF Request Processing Life Cycle with example.