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: • • • • • • •
Page navigation specification Standard user interface components like input fields, buttons, and links User input validation Easy error handling Java bean management Event handling Internationalization support
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: • • •
JDK 1.4 Tomcat 5.0 or any other servlet container (JBoss, Resin, JRun). We will use Tomcat in this example. Ant
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 file explanation jsfks Project folder with project name /ant This folder holds Ant build scripts including a default build.xml file. This folder is where you place your own Java source classes and /JavaSource properties files. This folder holds the actual Web application files used by the application /WebContent 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. This folder inside the WEB-INF folder holds compiled Java classes /classes along with properties files copied from JavaSource. This folder inside the WEB-INF folder holds libraries required by your /lib application, for example, third party Jar files. These two files inside the lib folder are library files included with the jsf-impl.jar JavaServer Faces v1.1 Reference Implementation. Every JSF application jsf-api.jar requires these files. This file inside the WEB-INF folder is the Web Application Deployment web.xml Descriptor for your application. This is an XML file describing the servlets and other components that make up your application. This file inside the WEB-INF folder is the JavaServer Faces facesconfiguration file. This file lists bean resources and navigation rules. We config.xml will cover this file in more detail later. This folder inside the WebContent folder holds JSP and HTML pages 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. 2. 3. 4. 5. 6. 7. 8.
Create JSP pages Define a navigation rule Create a managed bean Create a properties file Edit JSP pages Create an index.jsp file Compile the application 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. /pages/inputname.jsp greeting /pages/greeting.jsp
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-class>jsfks.PersonBean <managed-bean-scope>request
faces-config.xml Your final faces-config.xml file should look like this: /pages/inputname.jsp greeting /pages/greeting.jsp
<managed-bean> <managed-bean-name>personBean <managed-bean-class>jsfks.PersonBean <managed-bean-scope>request
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" %>
enter your name page
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" %>
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.
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 2 3 4 5
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" %> greeting page
,
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 ..
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://locahost:8080/jsfks/
Now, put this coding into the file: <jsp:forward page="/pages/inputname.jsf" />
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:
near the end of the server.xml file within the Host element just before the closing 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-class>jsfks.PersonBean <managed-bean-scope>request <managed-property> <property-name>personName <property-class>java.lang.String JavaJoe
You don't even need to recompile anything, just restart Tomcat and launch the application.