Document Information


Part I Introduction

1.  Overview

2.  Using the Tutorial Examples

Part II The Web Tier

3.  Getting Started with Web Applications

4.  JavaServer Faces Technology

5.  Introduction to Facelets

What Is Facelets?

Using Facelets Templates

Composite Components

Web Resources

6.  Expression Language

7.  Using JavaServer Faces Technology in Web Pages

8.  Using Converters, Listeners, and Validators

9.  Developing with JavaServer Faces Technology

10.  JavaServer Faces Technology: Advanced Concepts

11.  Using Ajax with JavaServer Faces Technology

12.  Composite Components: Advanced Topics and Example

13.  Creating Custom UI Components and Other Custom Objects

14.  Configuring JavaServer Faces Applications

15.  Java Servlet Technology

16.  Uploading Files with Java Servlet Technology

17.  Internationalizing and Localizing Web Applications

Part III Web Services

18.  Introduction to Web Services

19.  Building Web Services with JAX-WS

20.  Building RESTful Web Services with JAX-RS

21.  JAX-RS: Advanced Topics and Example

Part IV Enterprise Beans

22.  Enterprise Beans

23.  Getting Started with Enterprise Beans

24.  Running the Enterprise Bean Examples

25.  A Message-Driven Bean Example

26.  Using the Embedded Enterprise Bean Container

27.  Using Asynchronous Method Invocation in Session Beans

Part V Contexts and Dependency Injection for the Java EE Platform

28.  Introduction to Contexts and Dependency Injection for the Java EE Platform

29.  Running the Basic Contexts and Dependency Injection Examples

30.  Contexts and Dependency Injection for the Java EE Platform: Advanced Topics

31.  Running the Advanced Contexts and Dependency Injection Examples

Part VI Persistence

32.  Introduction to the Java Persistence API

33.  Running the Persistence Examples

34.  The Java Persistence Query Language

35.  Using the Criteria API to Create Queries

36.  Creating and Using String-Based Criteria Queries

37.  Controlling Concurrent Access to Entity Data with Locking

38.  Using a Second-Level Cache with Java Persistence API Applications

Part VII Security

39.  Introduction to Security in the Java EE Platform

40.  Getting Started Securing Web Applications

41.  Getting Started Securing Enterprise Applications

42.  Java EE Security: Advanced Topics

Part VIII Java EE Supporting Technologies

43.  Introduction to Java EE Supporting Technologies

44.  Transactions

45.  Resources and Resource Adapters

46.  The Resource Adapter Example

47.  Java Message Service Concepts

48.  Java Message Service Examples

49.  Bean Validation: Advanced Topics

50.  Using Java EE Interceptors

Part IX Case Studies

51.  Duke's Bookstore Case Study Example

52.  Duke's Tutoring Case Study Example

53.  Duke's Forest Case Study Example



Developing a Simple Facelets 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 javax.faces.webapp.FacesServlet instance

  • Adding managed bean declarations

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 whether you guessed the number correctly or incorrectly.

Developing a Managed Bean

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

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

package guessNumber;

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

public class UserNumberBean implements Serializable {

    private static final long serialVersionUID = 5443351151396868724L;
    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 managed bean as a resource with the JavaServer Faces implementation. The @SessionScoped annotation registers the bean scope as session.

Creating Facelets Views

To create a page or view, you add components to the pages, wire the components to managed 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, 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 library="images" name=""
                            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?
                    title="Type a number from 0 to 10:"
                <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; so 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 library="images" name=""
                            alt="Duke waving his hand"/>
                <h:outputText id="result" value="#{userNumberBean.response}"/>
            <h:commandButton id="back" value="Back" action="greeting"/>

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.0" 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.

Running the guessnumber Facelets Example

You can use either NetBeans IDE or Ant to build, package, deploy, and run the guessnumber example. The source code for this example is available in the tut-install/examples/web/guessnumber/ directory.

To Build, Package, and Deploy the guessnumber Example Using NetBeans IDE

  1. From the File menu, choose Open Project.
  2. In the Open Project dialog, navigate to:
  3. Select the guessnumber folder.
  4. Select the Open as Main Project check box.
  5. Click Open Project.
  6. In the Projects tab, right-click the guessnumber project and select Deploy.

    This option builds and deploys the example application to your GlassFish Server instance.

To Build, Package, and Deploy the guessnumber Example Using Ant

  1. In a terminal window, go to:
  2. Type the following command:

    This command calls the default target, which builds and packages the application into a WAR file, guessnumber.war, that is located in the dist directory.

  3. Make sure that the GlassFish Server is started.
  4. To deploy the application, type the following command:
    ant deploy

To Run the guessnumber Example

  1. Open a web browser.
  2. Type the following URL in your web browser:

    A web page opens.

  3. In the text field, type 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 the Back button to return to the main page.

    You can continue to guess until you get the correct answer.