A Simple JavaServer Faces Application

This section describes the process of developing a simple JavaServer Faces application. You'll see what features a typical JavaServer Faces application contains and what part each role has in developing the application.

Steps in the Development Process

Developing a simple JavaServer Faces application usually requires these tasks:

These tasks can be done simultaneously or in any order. However, the people performing the tasks will need to communicate during the development process. For example, the page author needs to know the names of the objects in order to access them from the page.

The example used in this section is the guessNumber application, located in the <INSTALL>/j2eetutorial14/examples/web/ directory. It asks you to guess a number between 0 and 10, inclusive. The second page tells you whether you guessed correctly. The example also checks the validity of your input. The system log prints Duke's number. Figure 17-2 shows what the first page looks like.

The greeting.jsp page of the guessNumber application

Figure 17-2 The greeting.jsp Page of the guessNumber Application

The source for the guessNumber application is located in the <INSTALL>/j2eetutorial14/examples/web/guessNumber/ directory created when you unzip the tutorial bundle (see About the Examples). A sample guessNumber.war is provided in <INSTALL>/j2eetutorial14/examples/web/provided-wars/.

To build this example, follow these steps:

  1. Go to <INSTALL>/j2eetutorial14/examples/web/guessNumber/.
  2. Run asant build.

To package and deploy the example using asant, follow these steps:

  1. Run asant create-war.
  2. Start the Application Server.
  3. Run asant deploy-war.

To learn how to configure the example, use deploytool to package and deploy it:

  1. Start the Application Server.
  2. Start deploytool.
  3. Create a web application called guessNumber by running the New Web Component wizard. Select FileRight ArrowNewRight ArrowWeb Component.
  4. In the New Web Component wizard:
    1.   Select the Create New Stand-Alone WAR Module radio button.
    2.   In the WAR File field, enter <INSTALL>/j2eetutorial14/examples/web/guessNumber/guessNumber.war.
    3.   The WAR Display Name field shows guessNumber.
    4. In the Context Root field, enter /guessNumber.
    5. Click Edit Contents.
    6. In the Edit Contents dialog box, navigate to <INSTALL>/j2eetutorial14/examples/web/guessNumber/build/. Select everything in the build directory and click Add.
    7. In the Edit Contents dialog box, go back to <INSTALL>/j2eetutorial14/examples/web/guessNumber/ and select faces-config.xml. Click Add.
    8. In the Contents of guessNumber pane, drag the faces-config.xml file from the root level to the WEB-INF directory.
    9. While in the Edit Contents dialog box, navigate to <J2EE_HOME>/lib/ and select the jsf-api.jar. Click Add, and then click OK.
    10. Click Next.
    11. Select the Servlet radio button.
    12. Click Next.
    13. Select javax.faces.webapp.FacesServlet from the Servlet Class combo box.
    14. In the Startup Load Sequence Position combo box, enter 1.
    15. Click Finish.
  5. In the Web Component tabbed panes:
    1. Select the FacesServlet web component that is contained in the guessNumber web application from the tree.
    2. Select the Aliases tab.
    3. Click Add, and enter /guess/* in the Aliases field.
    4. Select the guessNumber web component from the tree.
  6. Select FileRight ArrowSave.
  7. Deploy the application.
  8. Select ToolsRight ArrowDeploy.
  9. In the Connection Settings frame, enter the user name and password you specified when you installed the Application Server.
  10. Click OK.
  11. A pop-up dialog box will display the results of the deployment. Click Close.

To run the example, open the URL http://localhost:8080/guessNumber in a browser.

Creating the Pages

Creating the pages is the page author's responsibility. This task involves laying out UI components on the pages, mapping the components to beans, and adding other core tags.

Here is the greeting.jsp page, the first page of the guessNumber application:

  <HEAD> <title>Hello</title> </HEAD>  
  <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
  <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
  <body bgcolor="white">
    <h:form id="helloForm" >
      <h2>Hi. My name is Duke.  I'm thinking of a number from
      <h:outputText value="#{UserNumberBean.minimum}"/> to
      <h:outputText value="#{UserNumberBean.maximum}"/>.  
      Can you guess it?</h2>
      <h:graphicImage id="waveImg" url="/wave.med.gif" />
      <h:inputText id="userNo" 
          maximum="#{UserNumberBean.maximum}" />
      <h:commandButton id="submit" action="success"
        value="Submit" /> <p>
      <h:message style="color: red; 
        font-family: 'New Century Schoolbook', serif; 
        font-style: oblique; 
        text-decoration: overline" 

This page demonstrates a few important features that you will use in most of your JavaServer Faces applications. These features are described in the following subsections.

User Interface Component Model includes a table that lists all the component tags included with JavaServer Faces technology. Using the HTML Component Tags discusses the tags in more detail.

The form Tag

The form tag represents an input form that allows the user to input some data and submit it to the server, usually by clicking a button. All UI component tags that represent editable components (such as text fields and menus) must be nested inside the form tag. In the case of the greeting.jsp page, some of the tags contained in the form are inputText, commandButton, and message.

The outputText Tag

The outputText tag represents a label. The greeting.jsp page has two outputText tags. One of the tags displays the number 0. The other tag displays the number 10:

  <h:outputText value="#{UserNumberBean.minimum}"/>
  <h:outputText value="#{UserNumberBean.maximum}"/> 

The value attributes of the tags get the values from the minimum and maximum properties of UserNumberBean using value-binding expressions, which are used to reference data stored in other objects, such as beans. The page author could instead specify literal values using the value attributes of these tags. See Backing Bean Management for more information on value-binding expressions.

The inputText Tag

The inputText tag represents a text field component. In the guessNumber example, this text field takes an integer. The instance of this tag included in greeting.jsp has two attributes: id and value.

The id attribute corresponds to the ID of the component object represented by this tag. If you don't include an id attribute, the JavaServer Faces implementation will generate one for you. See Using the HTML Component Tags for more information. In this case, the inputText tag requires an id attribute because the message tag needs to refer to the userNo component.

The value attribute binds the userNo component value to the bean property UserNumberBean.userNumber, which holds the data entered into the text field. A page author can also bind a component instance to a property using the tag's binding attribute.

See Backing Bean Management for more information on creating beans, binding to bean properties, referencing bean methods, and configuring beans.

See The UIInput and UIOutput Components for more information on the inputText tag.

The commandButton Tag

The commandButton tag represents the button used to submit the data entered in the text field. The action attribute specifies an outcome that helps the navigation mechanism decide which page to open next. Defining Page Navigation discusses this further. See The UICommand Component for more information on the commandButton tag.

The message Tag

The message tag displays an error message if the data entered in the field does not comply with the rules specified by the LongRangeValidator implementation. The error message displays wherever you place the message tag on the page. The style attribute allows you to specify the formatting style for the message text. The for attribute refers to the component whose value failed validation, in this case the userNo component represented by the inputText tag in the greeting.jsp page. Note that the tag representing the component whose value is validated must include an id attribute so that the for attribute of the message tag can refer to it. See The UIMessage and UIMessages Components for more information on the message tag.

The validateLongRange Tag

By nesting the validateLongRange tag within a component's tag, the page author registers a LongRangeValidator onto the component. This validator checks whether the component's local data is within a certain range, defined by the validateLongRange tag's minimum and maximum attributes, which get the values from the minimum and maximum properties of UserNumberBean using the value-binding expressions #{UserNumberBean.minimum} and #{UserNumberBean.maximum}. The page author can instead specify literal values with these attributes. See Backing Bean Management for details on value-binding expressions. For more information on the standard validators included with JavaServer Faces technology, see Using the Standard Validators.

Defining Page Navigation

Defining page navigation involves determining which page to go to after the user clicks a button or a hyperlink. Navigation for the application is defined in the application configuration resource file using a powerful rule-based system. Here are the navigation rules defined for the guessNumber example:


Each navigation-rule element defines how to get from one page (specified in the from-view-id element) to the other pages of the application. The navigation-rule elements can contain any number of navigation-case elements, each of which defines the page to open next (defined by to-view-id) based on a logical outcome (defined by from-outcome).

The outcome can be defined by the action attribute of the UICommand component that submits the form, as it is in the guessNumber example:

<h:commandButton id="submit" action="success" 
  value="Submit" /> 

The outcome can also come from the return value of an action method in a backing bean. This method performs some processing to determine the outcome. For example, the method can check whether the password the user entered on the page matches the one on file. If it does, the method might return success; otherwise, it might return failure. An outcome of failure might result in the logon page being reloaded. An outcome of success might cause the page displaying the user's credit card activity to open. If you want the outcome to be returned by a method on a bean, you must refer to the method using a method-binding expression, using the action attribute, as shown by this example:

<h:commandButton id="submit" 
  action="#{userNumberBean.getOrderStatus}" value="Submit" /> 

To learn more about how navigation works and how to define navigation rules, see Navigation Model and Configuring Navigation Rules. For information on referencing an action method, see Referencing a Method That Performs Navigation. For information on writing an action method, see Writing a Method to Handle Navigation.

Developing the Beans

Developing beans is one responsibility of the application developer. The page author and the application developer--if they are two different people--will need to work in tandem to make sure that the component tags refer to the proper UI component properties, to ensure that the properties have the acceptable types, and to take care of other such details.

A typical JavaServer Faces application couples a backing bean with each page in the application. The backing bean defines properties and methods that are associated with the UI components used on the page. Each backing bean property is bound to either a component instance or its value.

A backing bean can also define a set of methods that perform functions for the component, such as validating the component's data, handling events that the component fires, and performing processing associated with navigation when the component is activated.

The page author binds a component's value to a bean property using the component tag's value attribute to refer to the property. Similarly, the page author binds a component instance to a bean property by referring to the property using the component tag's binding attribute.

Here is the UserNumberBean backing bean property that maps to the data for the userNo component:

Integer userNumber = null;
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.";

As you can see, this bean property is just like any other bean property: It has a set of accessor methods and a private data field. This means that you can reference beans you've already written from your JavaServer Faces pages.

A property can be any of the basic primitive and numeric types or any Java object type for which an appropriate converter is available. JavaServer Faces technology automatically converts the data to the type specified by the bean property. See Writing Component Properties for information on which types are accepted by which component tags.

You can also use a converter to convert the component's value to a type not supported by the component's data. See Creating a Custom Converter for more information on applying a converter to a component.

In addition to binding components and their values to backing bean properties using component tag attributes, the page author can refer to a backing bean method from a component tag. See Backing Bean Management for more information on referencing methods from a component tag.

Adding Managed Bean Declarations

After developing the backing beans to be used in the application, you need to configure them in the application configuration resource file so that the JavaServer Faces implementation can automatically create new instances of the beans whenever they are needed.

The task of adding managed bean declarations to the application configuration resource file is the application architect's responsibility. Here is a managed bean declaration for UserNumberBean:


One outputText tag on the greeting.jsp page binds its component's value to the minimum property of UserNumberBean. The other outputText tag binds its component's value to the maximum property of UserNumberBean.

<h:outputText value="#{UserNumberBean.minimum}"/> 
<h:outputText value="#{UserNumberBean.maximum}"/> 

As shown in the tags, the part of the expression before the . matches the name defined by the managed-bean-name element. The part of the expression after the . matches the name defined by the property-name element corresponding to the same managed-bean declaration.

Notice that the managed-property elements configure the minimum and maximum properties with values. These values are set when the bean is initialized, which happens when it is first referenced from a page.

Also notice that the application configuration resource file does not configure the userNumber property. Any property that does not have a corresponding managed-property element will be initialized to whatever the constructor of the bean class has the instance variable set to.

The JavaServer Faces implementation processes this file on application startup time. When the UserNumberBean is first referenced from the page, the JavaServer Faces implementation initializes it and stores it in session scope if no instance exists. The bean is then available for all pages in the application. For more information, see Backing Bean Management.