The Java EE 6 Tutorial, Volume I

Developing a Simple Facelets Application

This section describes the general steps involved in developing a JavaServer Faces application.

Developing a simple JavaServer Faces application, using Facelets technology usually requires these tasks:

In the next section some of the above tasks are described in more detail.

Creating a Facelets Application

The example used in this tutorial is the guessnumber application. The application presents you with a page that asks you to guess a number between 0 and 10, validates your input against a random number, and responds with another page that informs you, if you guessed the number correctly or incorrectly.

Developing a Backing Bean

In a typical JavaServer Faces application each page in the application connects to a backing bean (a type of managed bean). The backing bean defines the methods and properties that are associated with the components.

The following managed bean class, UserNumberBean.java, generates a random number between 0 and 10:

package guessNumber;

import java.util.Random;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped; 

@ManagedBean
@SessionScoped
public class UserNumberBean {
    Integer randomInt = null;
    Integer userNumber = null;
    String response = null;
    private long maximum=10;
    private long minimum=0;

    public UserNumberBean() {
        Random randomGR = new Random();
        randomInt = new Integer(randomGR.nextInt(10));
        System.out.println("Duke's number: " + randomInt);
    } 
    public void setUserNumber(Integer user_number) {
        userNumber = user_number;
    }

    public Integer getUserNumber() {
        return userNumber;
    }

    public String getResponse() {
        if ((userNumber != null) && (userNumber.compareTo(randomInt) == 0))
        {
            return "Yay! You got it!";
        }
        else
        {
            return "Sorry, " + userNumber + " is incorrect.";
        }
    }

    public long getMaximum() {
        return (this.maximum);
    }

    public void setMaximum(long maximum) {
        this.maximum = maximum;

    }

    public long getMinimum() {
        return (this.minimum);
    }

    public void setMinimum(long minimum) {
        this.minimum = minimum;

    }
}

Note the use of the @ManagedBean annotation which registers the backing bean as a resource with JavaServer Faces implementation. The @SessionScoped annotation registers the bean scope as session.

Creating Facelets Views

Creating a page or view is the responsibility of a page author. This task involves adding components on the pages, wiring the components to backing bean values and properties, and registering converters, validators, or listeners onto the components.

For the example application, XHTML web pages serve as the front end. The first page of the example application is a page called greeting.xhtml. A closer look at various sections of this web page provides more information.

The first section of the web page declares the content type for the page, which is XHTML:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

The next section declares the XML namespace for the tag libraries that are used in the web page:

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html">

The next section uses various tags to insert components into the web page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">

<h:head>
    <title>Facelets Guess Number Application</title>
</h:head>

<h:body>
    <h:form>
        <h:graphicImage value="#{resource['images:wave.med.gif']}"/>
    <h2>
     Hi, 
     <p>My name is Duke. I am thinking of a number between <b>
     #{userNumberBean.minimum} and #{userNumberBean.maximum}.
         </b> Can you guess it ?</p>
     
    <h:inputText
        id="userNo"
        value="#{userNumberBean.userNumber}">
        <f:validateLongRange
            minimum="#{userNumberBean.minimum}"
            maximum="#{userNumberBean.maximum}"/>
     </h:inputText>

     <h:commandButton id="submit" value="Submit" action="response.xhtml"/>
     <h:message showSummary="true" showDetail="false"
                style="color: red;
                 font-family: 'New Century Schoolbook', serif;
                 font-style: oblique;
                 text-decoration: overline"
                 id="errors1"
                 for="userNo"/>
    </h2>
    </h:form>
  </h:body>
</html>

Note the use of the Facelets HTML tags to add components, and the Facelets core tag to validate the user input. An inputText component accepts user input and sets the value of the backing bean property userNumber through the EL expression #{userNumberBean.userNumber}. The input value is validated for value range by the JavaServer Faces standard validator f:validateLongRange.

The image file wave.med.gif, is added to the page as a resource. For more details about the resources facility, see Resources.

The submit command button starts validation of the input data. Using implicit navigation, it redirects the client to another page response.xhtml, which shows the response to your input.

You can now create the second page, response.xhtml, with the following content:

<!DOCTYPE html
      PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html">

<h:head>
    <title>Guess Number Facelets Application</title>
</h:head>
 <h:body>
    <h:form>
        <h:graphicImage value="#{resource['images:wave.med.gif']}"/>
    <h2>
        <h:outputText id="result" value="#{userNumberBean.response}"/>
        
    </h2>

        <h:commandButton id="back" value="Back" action="greeting.xhtml"/>

    </h:form>
</h:body>
</html>

Configuring the Application

Configuring a JavaServer Faces application involves various configuration tasks which include adding managed-bean declarations, navigation rules and resources bundle declarations in the application configuration resource files such as faces-config.xml, and mapping the Faces Servlet in the web deployment descriptor file such as a web.xml file. Application configuration is an advanced topic covered in Java EE 6 Tutorial, Volume II: Advanced Topics.

If you are using an IDE such as NetBeans IDE, a web deployment descriptor is automatically created for you. In such IDE created web.xml files, change the default greeting page which is index.xhtml, to greeting.xhtml. Here is an example web.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>faces/greeting.xhtml</welcome-file>
    </welcome-file-list>
</web-app>

Note the use of parameter PROJECT_STAGE. ProjectStage is a context parameter identifying the status of a JavaServer Faces application in the software lifecycle.

The stage of an application can affect the behavior of the application. For example, if the project stage is defined as Development, debugging information is automatically generated for the user. If not defined by the user, the default project stage is considered as Production. Project Stage is covered in more detail in Java EE 6 Tutorial, Volume II: Advanced Topics.

Building, Packaging, Deploying and Running the Application

The example Facelets application described in this chapter can be built, packaged, and deployed using the Java EE 6 SDK with NetBeans IDE. For details on how to obtain this software and configure your environment to run the examples, see Chapter 2, Using the Tutorial Examples. The source code for this example is also available in the tut-install/examples/web/guessnumber directory.

ProcedureTo Create the Example Facelets Application with NetBeans IDE

To create the example Facelets project, use the following procedure.

  1. In NetBeans IDE, from the File menu, choose New Project.

    The New Project wizard opens.

  2. In the wizard, select Java Web as the category and Web Application as the project type and click Next.

    The New Web Application wizard opens.

  3. In the Project Name field, type guessNumber, and click Next.

  4. In the Server and Settings page, select Server as GlassFish v3 from the Server menu, select Java EE version as Java EE 6 Web from the Java EE version menu, and then click Next.

  5. In the Frameworks page, select the JavaServer Faces checkbox and click Finish.

    A new Project is created and is available in the Projects window. A default file, index.xhtml, is created and opened in the Editor.

ProcedureTo Create the Application

  1. Right-click the Project node, and select New->Java package.

  2. In the Package Name field, type guessNumber and click Finish.

    A new package is created and placed under Source Packages node of the Project.

  3. Right-click the Source Packages node and select New->Java Class.

  4. Type the name of the class file as UserNumberBean, select the name of package as guessNumber and click Finish.

    A new Java class file is created and opened in the IDE.

  5. Replace the content of the Java class file with the example code from the UserNumberBean.java file listed in Developing a Backing Bean, and save the file.

  6. Create two new XHTML pages and name them greeting.xhtml and response.xhtml respectively:

    1. Right-click the project node and choose New->Other.

      The New File wizard opens.

    2. Choose Category as Web and then File Type as XHTML and click Next.

    3. Enter greeting.xhtml in the XHTML File name field and click Finish.

      A new XHTML web page is created and placed under Web Pages node.

    4. Repeat the above steps but enter the name of file as response.xhtml to create a second web page.

  7. Edit the XHTML files and add Facelets content to them:

    1. Replace the content of greeting.xhtml with the example greeting.xhtml code listed in Creating Facelets Views and save the file.

    2. Similarly replace the content of response.xhtml with the example response.xhtml code and save the file.

  8. Add Duke's image as part of the application by copying the wave.med.gif image file from the tutorial example and saving it as a resource.

    1. Create a folder named resources under Web Pages.

    2. Create a subfolder, images under resources folder.

    3. Save the wave.med.gif image in resources/images folder.

  9. Edit the web.xml file to modify the welcome page to greeting.html.

  10. Right-click the Project Node and select Build from the menu, to compile and build the application.

  11. Right-click the Project Node and select Deploy, to deploy the application to Sun GlassFishTM Enterprise Server v3.

  12. Access the application by typing the following URL in the browser:


    http://localhost:8080/guessNumber