JavaServer Faces (JSF) Tutorial

JSF KickStart: A Simple JavaServer Faces Application

In this tutorial, we will show you an example of a JSF application developed without any special IDE. We won't dwell on the theory behind JSF here. There are plenty of sites and books that will do that for you. Instead, we will go quickly into the construction of this simple application that we hope can form the basis for you to start developing more advanced applications.

What Is JavaServer Faces?

Per our promise, we will keep the background simple. JavaServer Faces is a new framework for building Web applications using Java. JavaServer Faces provides you with the following main features:

JSF provides the common plumbing for any Web application allowing you to concentrate on your specific application (instead of worrying about things like how to create a link from one page to another). This will become clearer as we go along.

What Will You Need?

You will need the following to complete this tutorial:

We will provide you with many of the project files so that you don't need to create them yourself. We will be concentrating primarily on the actual JSF application, not on creating Ant scripts or web.xml files. These files will be provided for you. You will just need to copy and paste content from this tutorial.

What Are We Going to Build?

You may have guessed by now. We are going to build a "Hello, world" (actually "Welcome to JSF, <user>!") type application using JSF. This should give you a solid start with JSF.

We will create two pages. The first page will prompt a user to enter his or her name and the second page will show a greeting. This is a sample of the input page:

and this is a sample of the result page:

JSF Application Structure

We have provided you with a pre-made project structure skeleton in an archive called jsfks.zip that you can download and unzip. After unzipping you should have the following structure:

jsfks
   /ant
      build.xml 
   /JavaSource
   /WebContent
      /WEB-INF
         /classes
         /lib
            jsf-impl.jar
            jsf-api.jar
         faces-config.xml
         web.xml
      /pages
This is a typical skeleton structure for a Web application like JSF. Now, let's go through the different parts of the skeleton structure.

folder or fileexplanation
jsfks Project folder with project name
  /ant This folder holds Ant build scripts including a default build.xml file.
  /JavaSource This folder is where you place your own Java source classes and properties files.
  /WebContent This folder holds the actual Web application files used by the application server or servlet container.
    /WEB-INF This folder inside the WebContent folder holds files that are used as part of the runtime Web application but are hidden from the browser.
      /classes This folder inside the WEB-INF folder holds compiled Java classes along with properties files copied from JavaSource.
      /lib This folder inside the WEB-INF folder holds libraries required by your application, for example, third party Jar files.
        jsf-impl.jar
        jsf-api.jar
These two files inside the lib folder are library files included with the JavaServer Faces v1.1 Reference Implementation. Every JSF application requires these files.
      web.xml This file inside the WEB-INF folder is the Web Application Deployment Descriptor for your application. This is an XML file describing the servlets and other components that make up your application.
      faces-config.xml This file inside the WEB-INF folder is the JavaServer Faces configuration file. This file lists bean resources and navigation rules. We will cover this file in more detail later.
    pages This folder inside the WebContent folder holds JSP and HTML presentation pages.

We have already provided you with two complete project files in the the project, web.xml and build.xml, so that you don't have to spend time creating these. (This tutorial is not about creating these kinds of files.)

The Steps

We will complete the following steps:

  1. Create JSP pages
  2. Define a navigation rule
  3. Create a managed bean
  4. Create a properties file
  5. Edit JSP pages
  6. Create an index.jsp file
  7. Compile the application
  8. Deploy and run the application
Let's get started.

Downloadable Version of Finished Project

But first note that we have also provided you with the finished application in case you just want to just run it and skip most of the steps. If you want to do this, you can download and unzip jsfks-done.zip. Then skip to the "compile" step and go from there.

Creating JSP Pages

Create the inputname.jsp and greeting.jsp files in WebContent/pages/. You only need to create the JSP files. The directory structure already exists.

These files will act as place holders for now. We will complete the content of the files a little bit later.

Now that we have the two JSP pages, we can create a navigation rule.

Navigation

Navigation is the heart of JavaServer Faces. The navigation rule for this application is described in the faces-config.xml file. This file already exists in the skeleton directory structure. You just need to create its contents.

In our application, we just want to go from inputname.jsp to greeting.jsp. As a diagram, it would look something like this:


Image from Exadel Studio Pro

The navigation rule shown in the picture is defined below. The rule says that from the view (page) inputname.jsp go to the view (page) greeting.jsp, if the "outcome" of executing inputname.jsp is greeting. And that's all there is to this.

<navigation-rule>
  <from-view-id>/pages/inputname.jsp</from-view-id>
  <navigation-case>
    <from-outcome>greeting</from-outcome>
    <to-view-id>/pages/greeting.jsp</to-view-id>
  </navigation-case>
</navigation-rule>

This is, of course, a very simple navigation rule. You can easily create more complex ones. To read more about navigation rules, visit the JSP Navigation Example forum item.

Creating the Managed Bean

Next, we will create a jsfks folder inside the JavaSource folder. Inside this jsfks folder, we will create a PersonBean.java file. This class is straight-forward. It's a simple Java bean with one attribute and setter/getter methods. The bean simply captures the name 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. (Please note that the field name in the JSP file must exactly match the attribute name in the bean.)

PersonBean.java

Put this code in the file:

package jsfks;

public class PersonBean {

   String personName;
	
   /**
   * @return Person Name
   */
   public String getPersonName() {
      return personName;
   }

   /**
   * @param Person Name
   */
   public void setPersonName(String name) {
      personName = name;
   }
}

Later you will see how to "connect" this bean with the JSP page.

Declaring the Bean in faces-config.xml

Now, the second part of faces-config.xml describes our Java bean that we created in the previous steps. This section defines a bean name PersonBean. The next line is the full class name, jsfks.PersonBean. request sets the bean scope in the application.

<managed-bean>
  <managed-bean-name>personBean</managed-bean-name>
  <managed-bean-class>jsfks.PersonBean</managed-bean-class>
  <managed-bean-scope>request</managed-bean-scope>
</managed-bean>

faces-config.xml

Your final faces-config.xml file should look like this:

<?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>
  <navigation-rule>
   <from-view-id>/pages/inputname.jsp</from-view-id>
    <navigation-case>
     <from-outcome>greeting</from-outcome>
     <to-view-id>/pages/greeting.jsp</to-view-id>
   </navigation-case>
  </navigation-rule>
  <managed-bean>
    <managed-bean-name>personBean</managed-bean-name>
    <managed-bean-class>jsfks.PersonBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
  </managed-bean>
</faces-config>

Creating a Properties File (Resource Bundle)

A properties file is just a file with param=value pairs. We use the messages stored in the properties file in our JSP pages. Keeping the messages separate from the JSP page allows us to quickly modify the messages without editing the JSP page.

Let's create a bundle folder in the JavaSource/jsfks folder and then a messages.properties file in the bundle folder. We need to place it in the JavaSource folder so that during project compilation, this properties file will be copied to the classes folder where the runtime can find it.

messages.properties

Put this text in the properties file:

inputname_header=JSF KickStart
prompt=Tell us your name:
greeting_text=Welcome to JSF
button_text=Say Hello
sign=!

We now have everything to create the JSP pages.

Editing the JSP Pages

Two pages should already have been created in jsks/WebContent/pages.

inputname.jsp

Put the following coding into this file:

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:loadBundle basename="jsfks.bundle.messages" var="msg"/>

<html>
 <head>
  <title>enter your name page</title>
 </head>
 <body>
   <f:view>
     <h1>
      <h:outputText value="#{msg.inputname_header}"/>
     </h1>
     <h:form id="helloForm">
      <h:outputText value="#{msg.prompt}"/>
      <h:inputText value="#{personBean.personName}" />
      <h:commandButton action="greeting" value="#{msg.button_text}" />
     </h:form>
   </f:view>
 </body>
</html>  

Now, let's explain the important sections in this file after displaying the code for each section starting from the top.

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>            
<f:loadBundle basename="jsfks.bundle.messages" var="msg"/>
The first line of these three is a directive that tells us where to find JSF tags that define HTML elements and the second directive tells us where to find JSF tags that define core JSF elements. The third line loads our properties file (resource bundle) that holds messages that we want to display in our JSP page.

<h:outputText value="#{msg.inputname_header}"/>
This tag simply tells us to look in the resource bundle that we defined at the top of the page. Then, look up the value for inputname_header in that file and print it here.

1 <h:form id="helloForm">
2   <h:outputText value="#{msg.prompt}"/>
3   <h:inputText id="name" value="#{personBean.personName}" />
4   <h:commandButton action="greeting" value="#{msg.button_text}" />
5 </h:form>
Line 1. Creates an HTML form using JSF tags.
Line 2. Prints a message from the properties file using the value of prompt.
Line 3. Creates an HTML input text box. The id is just the id of this field. In the value attribute we connect (bind) this field to the managed bean attribute that we created before.
Line 4. JSF tags for the HTML form's submit button. The button's value is being retrieved from the properties file. While the button's action attribute is set to greeting which matches the navigation-outcome in faces-config.xml file. That's how JSF knows where to go next.

greeting.jsp

Put this coding inside the second JSP file:

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:loadBundle basename="jsfks.bundle.messages" var="msg"/>

<html>
  <head>
   <title>greeting page</title>
  </head>    
  <body>
     <f:view>
     	<h3>
 	 <h:outputText value="#{msg.greeting_text}" />,
 	 <h:outputText value="#{personBean.personName}" />
         <h:outputText value="#{msg.sign}" />
    	</h3>
     </f:view>
 </body>	
</html> 

This page is very simple. The first three lines are identical to our first page. Theses lines import JSF tag libraries and our properties file (resource bundle) with the messages.

The main code of interest to us is between the <h3>..</h3> tags. The first line will take a message from the resource bundle and print it on the page. The second line will access a Java bean, specifically the bean attribute personName, and also print its contents on the page.

Once this page is displayed in a Web browser, you will see something like this:

Welcome to JSF, name!

Creating the index.jsp File

We will now create a third JSP file that doesn't actually function as a presentation page. It uses a JSP tag to "forward" to the inputname.jsp page.

Create the index.jsp file inside the WebContent folder. Note that this file is not created in the pages folder like the previous JSP files.

Having an index.jsp file will allow us to start the application like this:

http://localhost:8080/jsfks/

Now, put this coding into the file:

<html>
 <body>
  <jsp:forward page="/pages/inputname.jsf" />
 </body>
</html>
If you look at the path for the forward, you'll notice the file suffix is .jsf and not .jsp. This is used here, because in the web.xml file for the application *.jsf is the URL pattern used to signal that the forwarded page should be handled by the JavaServer Faces servlet within Tomcat.

We are almost done with this example.

Compiling

An Ant build script is provided for you. To build the application run the build.xml script from the ant folder:

ant build

Deploying

Before you can run this application within the servlet container, we need to deploy it. We will use null (link) deployment to deploy the application in-place. To do this we need to register a context in Tomcat's {TomcatHome}\conf\server.xml file.

To do this, insert this code:

<Context debug="0"
docBase="Path_to_WebContent"
path="/jsfks" reloadable="true"/> 
near the end of the server.xml file within the Host element just before the closing </Host> tag. Of course, Path_to_WebContent needs to be replaced with the exact path on your system to the WebContent folder inside the jsfks folder (for example, C:/examples/jsfks/WebContent).

Running

Next, start the Tomcat server (probably using the script startup.bat in Tomcat's bin directory). When Tomcat is done loading, launch a web browser and enter: http://localhost:8080/jsfks. (Port 8080 is the default port in Tomcat. Your setup, though, might possibly be different).

Try This!

It's always a good learning experience to modify the application after you are done. Let's try a simple modification.

Let's say we want to initialize the name value. In other words, when we first run the application, the input text field should have a value already displayed.

It is very simply to do this in JSF. We can provide an initial value in the faces-config.xml file, in the managed bean section. The lines in bold from this section show what we need to add. These lines declare a managed bean property of type java.lang.String and then set its value to JavaJoe.

<managed-bean>
  <managed-bean-name>personBean</managed-bean-name>
  <managed-bean-class>jsfks.PersonBean</managed-bean-class>
  <managed-bean-scope>request</managed-bean-scope>
  <managed-property>
    <property-name>personName</property-name>
    <property-class>java.lang.String</property-class>
    <value>JavaJoe</value>
  </managed-property>
</managed-bean>

You don't even need to recompile anything, just restart Tomcat and launch the application.

Next Step

Try the next tutorial - adding simple validation to your project.


Tutorials
Training

Exadel, Inc. Copyright 2005