Java Platform, Enterprise Edition: The Java EE Tutorial

8.3 Developing a Simple Facelets Application: The guessnumber-jsf Example Application

This section describes the general steps involved in developing a JavaServer Faces application. The following tasks are usually required:

  • Developing the managed beans

  • Creating the pages using the component tags

  • Defining page navigation

  • Mapping the FacesServlet instance

  • Adding managed bean declarations

8.3.1 Creating a Facelets Application

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

The source code for this application is in the tut-install/examples/web/jsf/guessnumber-jsf/ directory. Developing a Managed Bean

In a typical JavaServer Faces application, each page of the application connects to a managed bean that serves as a backing bean. The backing bean defines the methods and properties that are associated with the components. In this example, both pages use the same backing bean.

The following managed bean class,, generates a random number from 0 to 10 inclusive:

package javaeetutorial.guessnumber;

import java.util.Random;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named; 

public class UserNumberBean implements Serializable {

    private static final long serialVersionUID = 5443351151396868724L;
    Integer randomInt = null;
    Integer userNumber = null;
    String response = null;
    private int maximum = 10;
    private int minimum = 0;

    public UserNumberBean() {
        Random randomGR = new Random();
        randomInt = new Integer(randomGR.nextInt(maximum + 1));
        // Print number to server log
        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 "Sorry, " + userNumber + " is incorrect.";
        } else {
            return "Yay! You got it!";

    public int getMaximum() {
        return (this.maximum);

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

    public int getMinimum() {
        return (this.minimum);

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

Note the use of the @Named annotation, which makes the managed bean accessible through the EL. The @SessionScoped annotation registers the bean scope as session to enable you to make multiple guesses as you run the application. Creating Facelets Views

To create a page or view, you add components to the pages, wire the components to backing bean values and properties, and register converters, validators, or listeners on 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:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 

The next section specifies the language of the XHTML page and then declares the XML namespace for the tag libraries that are used in the web page:

<html lang="en"

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

        <h:outputStylesheet library="css" name="default.css"/>
        <title>Guess Number Facelets Application</title>
            <h:graphicImage value="#{resource['']}"
                            alt="Duke waving his hand"/>
                Hi, my name is Duke. I am thinking of a number from
                #{userNumberBean.minimum} to #{userNumberBean.maximum}.
                Can you guess it?
            <p><h:inputText id="userNo"
                            title="Enter a number from 0 to 10:"
                   <f:validateLongRange minimum="#{userNumberBean.minimum}"
                <h:commandButton id="submit" value="Submit"
            <h:message showSummary="true" showDetail="false"
                       style="color: #d20005;
                       font-family: 'New Century Schoolbook', serif;
                       font-style: oblique;
                       text-decoration: overline"

Note the use of the following tags:

  • Facelets HTML tags (those beginning with h:) to add components

  • The Facelets core tag f:validateLongRange to validate the user input

An h:inputText tag accepts user input and sets the value of the managed bean property userNumber through the EL expression #{userNumberBean.userNumber}. The input value is validated for value range by the JavaServer Faces standard validator tag f:validateLongRange.

The image file,, is added to the page as a resource, as is the style sheet. For more details about the resources facility, see Web Resources.

An h:commandButton tag with the ID submit starts validation of the input data when a user clicks the button. Using implicit navigation, the tag redirects the client to another page, response.xhtml, which shows the response to your input. The page specifies only response, which by default causes the server to look for response.xhtml.

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

<html lang="en"

        <h:outputStylesheet library="css" name="default.css"/>
        <title>Guess Number Facelets Application</title>
            <h:graphicImage value="#{resource['']}"
                            alt="Duke waving his hand"/>
                <h:outputText id="result" value="#{userNumberBean.response}"/>
            <h:commandButton id="back" value="Back" action="greeting"/>

This page also uses implicit navigation, setting the action attribute for the Back button to send the user to the greeting.xhtml page.

8.3.2 Configuring the Application

Configuring a JavaServer Faces application involves mapping the Faces Servlet in the web deployment descriptor file, such as a web.xml file, and possibly adding managed bean declarations, navigation rules, and resource bundle declarations to the application configuration resource file, faces-config.xml.

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

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="" 
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-name>Faces Servlet</servlet-name>

Note the use of the context parameter PROJECT_STAGE. This parameter identifies 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 Production.

8.3.3 Running the guessnumber-jsf Facelets Example

You can use either NetBeans IDE or Maven to build, package, deploy, and run the guessnumber-jsf example. To Build, Package, and Deploy the guessnumber-jsf Example Using NetBeans IDE

  1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server).

  2. From the File menu, choose Open Project.

  3. In the Open Project dialog box, navigate to:

  4. Select the guessnumber-jsf folder.

  5. Click Open Project.

  6. In the Projects tab, right-click the guessnumber-jsf project and select Build.

    This option builds the example application and deploys it to your GlassFish Server instance. To Build, Package, and Deploy the guessnumber-jsf Example Using Maven

  1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server).

  2. In a terminal window, go to:

  3. Enter the following command:

    mvn install

    This command builds and packages the application into a WAR file, guessnumber-jsf.war, that is located in the target directory. It then deploys it to the server. To Run the guessnumber-jsf Example

  1. Open a web browser.

  2. Enter the following URL in your web browser:

  3. In the field, enter a number from 0 to 10 and click Submit.

    Another page appears, reporting whether your guess is correct or incorrect.

  4. If you guessed incorrectly, click Back to return to the main page.

    You can continue to guess until you get the correct answer, or you can look in the server log, where the UserNumberBean constructor displays the correct answer.

Close Window

Table of Contents

Java Platform, Enterprise Edition: The Java EE Tutorial

Expand | Collapse