• Loading
    • Java Server Faces

      Learning Objectives
      After completing this session, you will be able to:
      • Explain JSF Specification and API
      • Explain how MyFaces works

      What are Java Server Faces?

      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.
      You will need the following to complete this tutorial:
      • JDK
      • Tomcat or any other servlet container (JBoss, Resin, JRun).
      • Ant

      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.

      You may have guessed by now. We are going to build a "Hello, world" (actually "Welcome to JSF, <user>!") type application using 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 with Example
      The project structure is as follows:
      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.
      /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.

      Steps in creating JSF Application:
      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

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

      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.

      Creating the Manages 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.)


      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.


      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" 
      <managed-bean-class>jsfks.PersonBean</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> 

      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.


      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 
      We now have everything to create the JSP pages.

      Editing the JSP Pages:

      Two pages should already have been created in jsks/WebContent/pages.
      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"/> 
      <title>enter your name page</title> 
      <h:outputText value="#{msg.inputname_header}"/> 
      <h:form id="helloForm"> 
      <h:outputText value="#{msg.prompt}"/> 
      <h:inputText value="#{personBean.personName}" /> 
      <h:commandButton action="greeting" value="#{msg.button_text}" /> 
      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 .
      • 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.


      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"/> 
      <title>greeting page</title> 
      <h:outputText value="#{msg.greeting_text}" />, 
      <h:outputText value="#{personBean.personName}" /> 
      <h:outputText value="#{msg.sign}" /> 
      This page is very simple. The first three lines are identical to our first page. These 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:
      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.


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

      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" 
      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 the application:

      • 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).


      • In this chapter, we learned about the basics of JavaServer Pages technology and serverside includes.
      • We briefly compared JSP pages to servlets and discussed when it is appropriate to use one or the other.
      • We also discussed the two JSP architectural models and how they differ in their request-handling process.

      Test your Understanding

      • What is JavaServer Faces?
      • How to pass a parameter to the JSF application using the URL string?
      • How to add context path to URL for outputLink?
      • How to get current page URL from backing bean?
      • How to access web.xml init parameters from java code?
      • How to access web.xml init parameters from jsp page?
      • How to terminate the session?
      • How to reload the page after ValueChangeListener is invoked?

    Disclaimer: Users of techforum4u.com are responsible for ensuring that any material they post (article, blog posts, images or other mulitimedia content) does not violate or infringe upon the copyright, patent, trademark, or any personal or proprietary rights of any third party, and is posted with the permission of the owner of such rights.Anyone who violates these rules may have their access privileges removed without warning.