Download
FAQ
History
PrevHomeNext API
Search
Feedback
Divider

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 package, deploy, and execute this example, follow these steps:

  1. Go to <INSTALL>/j2eetutorial14/examples/web/guessNumber/.
  2. Run asant build.
  3. Start the Sun Java System Application Server Platform Edition 8.
  4. Start deploytool.
  5. Create a Web application called guessNumber by running the New Web Component wizard. Select FileRight ArrowNew Web Component.
  6. In the New Web Component wizard:
    1.   Select the Create New Stand-Alone WAR Module radio button.
    2.   In the WAR Location field, enter <INSTALL>/j2eetutorial14/examples/web/guessNumber/guessNumber.war.
    3.   In the WAR Name field, enter 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 the greeting.jsp, index.jsp, and response.jsp JSP pages, the wave.med.gif file, the guessNumber package, and faces-config.xml, which is located in the WEB-INF directory. Click Add.
    7. In the Contents of guessNumber field, drag the faces-config.xml file from the root level to the WEB-INF directory.
    8. While in the Edit Contents dialog box, navigate to <J2EE_HOME>/lib/ and select the jsf-api.jar. Click Add, and then click OK.
    9. Click Next.
    10. Select the Servlet radio button.
    11. Click Next.
    12. Select javax.faces.webapp.FacesServlet from the Servlet Class combo box.
    13. In the Startup Load Sequence Position combo box, enter 1.
    14. Click Finish.
  7. 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.
  8. Select FileRight ArrowSave.
  9. Deploy the application.
  10. Select ToolsRight ArrowDeploy.
  11. In the Connection Settings frame, enter the user name and password you specified when you installed the Application Server.
  12. Click OK.
  13. A pop-up dialog box will display the results of the deployment. Click Close.
  14. 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 /guessNumber/web/greeting.jsp page from the guessNumber application:

<HTML>
  <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">
  <f:view>
    <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" 
        value="#{UserNumberBean.userNumber}">
        <f:validateLongRange minimum="0" maximum="10" />
      </h:inputText>      
      <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" 
        id="errors1" 
        for="userNo"/>
    </h:form>
  </f:view>
</HTML>  

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 buttons) must be nested inside the form tag. In the case of the guessNumber example, these tags are inputText, commandButton, and message.

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 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 messages 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. In the case of the guessNumber example, the data must be between 0 and 10, inclusive. 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. The JavaServer Faces navigation model is explained in Navigation Model. Configuring Navigation Rules explains how to define the navigation rules for an entire application.

Navigation for the application is defined in the application configuration file using a powerful rule-based system. Here are the navigation rules defined for the guessNumber example:

<navigation-rule>
  <from-view-id>/greeting.jsp</from-view-id>
  <navigation-case>
    <from-outcome>success</from-outcome>
    <to-view-id>/response.jsp</to-view-id>
  </navigation-case>
</navigation-rule>
<navigation-rule>
  <from-view-id>/response.jsp</from-view-id>
  <navigation-case>
    <from-outcome>success</from-outcome>
    <to-view-id>/greeting.jsp</to-view-id>
  </navigation-case>
</navigation-rule> 

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 a new instance of the bean whenever it is 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:

<managed-bean>
  <managed-bean-name>UserNumberBean</managed-bean-name>
  <managed-bean-class>
    guessNumber.UserNumberBean
  </managed-bean-class>
  <managed-bean-scope>session</managed-bean-scope>
  <managed-property>
    <property-name>minimum</property-name>
    <property-class>long</property-class>
    <value>0</value>
  </managed-property>
  <managed-property>
    <property-name>maximum</property-name>
    <property-class>long</property-class>
    <value>10</value>
  </managed-property>
</managed-bean> 

One outputText tag on the greeting.jsp page binds its component to the minimum property of UserNumberBean. The other outputText tag binds its component to the maximum property of UserNumberBean. Here are these tags again:

<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 class has the instance variable set to.

The JavaServer Faces implementation processes this file on application startup time. When the UserNameBean 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.

Divider
Download
FAQ
History
PrevHomeNext API
Search
Feedback
Divider

All of the material in The J2EE(TM) 1.4 Tutorial is copyright-protected and may not be published in other works without express written permission from Sun Microsystems.