Document Information

Preface

Part I Introduction

1.  Overview

2.  Using the Tutorial Examples

Part II The Web Tier

3.  Getting Started with Web Applications

4.  Java Servlet Technology

5.  JavaServer Faces Technology

6.  Introduction to Facelets

What's Facelets?

Advantages of Facelets

Authoring Facelets Pages

Tag Libraries and EL Support

Tag Library Support

Unified EL Support

7.  Using JavaServer Faces Technology in Web Pages

8.  Developing with JavaServer Faces Technology

9.  Configuring JavaServer Faces Applications

Part III Web Services

10.  Introduction to Web Services

11.  Building Web Services with JAX-WS

12.  Building RESTful Web Services with JAX-RS and Jersey

Part IV Enterprise Beans

13.  Enterprise Beans

14.  Getting Started with Enterprise Beans

15.  Running the Enterprise Bean Examples

Part V Persistence

16.  Introduction to the Java Persistence API

17.  Running the Persistence Examples

18.  The Java Persistence Query Language

Part VI Security

19.  Introduction to Security in the Java EE Platform

20.  Using Java EE Security

21.  Securing Java EE Applications

22.  Securing Web Applications

Part VII Java EE Supporting Technologies

23.  Introduction to Java EE Supporting Technologies

24.  Transactions

25.  Resource Connections

Index

 

Developing a Simple JavaServer Faces Application

This section describes the general steps involved in developing a simple JavaServer Faces application using Facelets, from the perspective of different development roles. These roles are:

  • Page author, who creates pages by using UI components with the help of the JavaServer Faces tag libraries

  • Application developer, who programs custom converters, validators, listeners, and backing beans

  • Component author, who creates custom UI components and renderers

  • Application architect, who configures the application, including defining the navigation rules, configuring custom objects, and creating deployment descriptors

Creating a Facelets application

Developing a simple JavaServer Faces application usually requires these tasks:

  • Developing the backing beans

  • Creating the pages using the UI component and core tags

  • Defining page navigation in the application configuration resource file

  • Mapping the FacesServlet instance

  • Adding managed bean declarations to the application configuration resource file

The example used in this section is a simple guessNumber application. The application presents you with a page that asks you to guess a number between 0 and 10, validates your input, and responds with another page that tells you whether you guessed the number correctly.

Developing a Backing Bean

Developing managed beans is the responsibility of an application developer. A typical JavaServer Faces application connects a managed bean to each page in the application. The backing bean defines methods and properties associated with the UI components used on the pages.

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

/*
 * Copyright 2007 Sun Microsystems, Inc.
 * All rights reserved.  You may not modify, use,
 * reproduce, or distribute this software except in
 * compliance with  the terms of the License at:
 * http://developer.sun.com/berkeley_license.html
 */
*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */ 
package guessNumber;
import java.util.Random;

public class UserNumberBean {
    Integer randomInt = null;
    Integer userNumber = null;
    String response = null;
    private boolean maximumSet = false;
    private boolean minimumSet = false;
    private long maximum = 0;
    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;
        this.maximumSet = true;
    }

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

    public void setMinimum(long minimum) {
        this.minimum = minimum;
        this.minimumSet = true;
    }
}
Creating Facelets Views

Creating a page or view is the page author's responsibility. This task involves laying out UI components on the pages, mapping the components to beans, and adding tags that register converters, validators, or listeners onto the components.

For the example application, create a couple of web pages that will serve as the application front end. The first view that you create can be called greeting.xhtml and that will be the first page of the application.

The first section of the 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 will declare the XML namespace for the tag libraries:

<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 UI components into the view:

<head>
    <title>Guess Number Facelets Application</title>
</head>
<body>
    <h:form>
    <h2>
     <h:graphicImage id="waveImg" url="/wave.med.gif" />
     Hi my name is Duke. I am thinking of a number between <b>
     <h:outputText value="#{UserNumberBean.minimum}"/> to
       &nbsp;&nbsp;</b>
     <h:outputText value="#{UserNumberBean.maximum}"/>.
     <p>
      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"
          action="success" value="submit" />
      <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>
</body>
</html>

While the html tags are used to express UI components, the core tag is used to validate the input.

You can now create a second page, response.xhtml, that will show the response for your input:

<?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">
<html xmlns="http://www.w3.org/1999/xhtml" 
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html">
<head>
    <title>Guess Number Facelets Application</title>
</head>
 <body>
    <h:form>
      <h:graphicImage id="waveImg" url="/wave.med.gif" alt="Duke waving" />
    <h2>
     <h:outputText id="result"
      value="#{UserNumberBean.response}"/></h2>
    <h:commandButton id="back" value="back" action="success"/>
    <p>
    </p>
    </h:form>
</body>
</html>

In addition, you can create a simple index.html page as the first page of application. This page will simply redirect the user to the greeting page:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title></title>
    <meta http-equiv="Refresh" content="0;url=guessNumber/greeting.xhtml"> 
      </head>
  <body>
    TODO write content
  </body>
</html>
Creating a Resource Bundle

You can also use an application message resource to inform the user of non-numerical input errors. This can be done by creating a resource bundle in the package that contains static error messages.

JavaServer Faces technology provides standard error messages that display on the page when conversion or validation fails. In some cases, you might need to override the standard message. For example, if a user were to enter a letter into the text field on greeting.jsp, the following error message would be displayed:

User Number: ’m’ must be a number between -2147483648 and 2147483647 Example: 9346

This is wrong because the field really only accepts values from 0 through 10.

To override this message, you add a converterMessage attribute on the inputText tag in the greeting.xhtml page. This attribute references the custom error message:

<h:inputText id="userNo" label="User Number"
         value="#{UserNumberBean.userNumber}"
         converterMessage="#{ErrMsg.userNoConvert}">
...
</h:inputText>

The expression that is used by the converterMessage, references the userNoConvert key of the ErrMsg resource bundle.

This message is stored in the resource bundle, ApplicationMessages.properties:

userNoConvert=The value you entered is not a number.

The application architect must define the message in the resource bundle and configure the resource bundle. See Adding Resource Bundle Declarations for more information on this process.

Configuring the Application

The last and most important part of creating a JavaServer Faces application is configuring an application configuration file. The application configuration file defines how the application is processed. Configuring the application is the responsibility of the application architect.

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:

<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>

This declaration configures UserNumberBean so that its minimum property is initialized to 0, its maximum property is initialized to 10, and it is added to session scope when it is created.

A page author can use the unified EL to access one of the bean’s properties, like this:

<h:outputText value="#{UserNumberBean.minimum}"/>
Adding Resource Bundle Declarations

If the standard error messages don’t meet your needs, you can create new ones in resource bundles and configure the resource bundles in your application configuration resource file.

The resource bundle is configured in the application configuration file:

<application>
    <resource-bundle>
        <base-name>guessNumber.ApplicationMessages</base-name>
        <var>ErrMsg</var>
    </resource-bundle>
</application>

The base-name element indicates the fully-qualified name of the resource bundle. The var element indicates the name by which page authors refer to the resource bundle with the expression language. Here is the inputText tag once again:

<h:inputText id="userNo" label="User Number"
    value="#{UserNumberBean.userNumber}"
        converterMessage="#{ErrMsg.userNoConvert}">
        ...
</h:inputText>

The expression on the converterMessage attribute references the userNoConvert key of the ErrMsg resource bundle.

Adding Page Navigation Rules

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 is one of the navigation rules defined for the guessNumber example:

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

This navigation rule states that when the button on the greeting page is clicked, the application will navigate to response.jsp if the navigation system is given a logical outcome of success.

In the case of the guessNumber example, the logical outcome is defined by the action attribute of the UICommand component that submits the form:

<h:commandButton id="submit" action="success"
     value="Submit" />
Web Application Deployment Descriptor

The above steps have configured the application. You can now add a web application deployment descriptor to the application. You will need to define the servlet class and the provide the necessary context path for the application. For example, you can add the following parameters to a web.xml file:

<servlet>
     <display-name>FacesServlet</display-name>
     <servlet-name>FacesServlet</servlet-name>
     <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
     <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>FacesServlet</servlet-name>
        <url-pattern>/guess/*</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>

The application can now be bundled into a server-deployable war file.

Building, Packaging, Deploying and Running the Application

The sample 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.

To Create the Example Facelets Application Project

To create a new Project for the sample Facelets application, use the following procedure:

  1. In the NetBeans IDE, select Files->New.
  2. Select Java Web as the project type and click Next.
  3. Select Server as GlassFish v3, Java EE version as Java EE 6, and click Next.
  4. Select Frameworks as JavaServer Faces and click Next.
  5. Enter the project name as guessNumber, and accept defaults for project location and project folder.
  6. Click Finish.

    A new Project is created and is available in the Project panel. You can either use the WelcomeJSF.jsp file or replace it with a simple index.html file.

To Create the Sample Application
  1. Right-click the Project node, and select New->Java package.
  2. Enter the name of package as guessNumber and click Finish.

    A new package is created and placed under Resources Node of the Project.

  3. Right-click the resources node and select New->Java Class.
  4. Enter the name of the class file as UserNumberBean, select the package as guessNumber, and click Finish.

    A new Java 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 listed above, and save the file.
  6. Create a new resource bundle for custom error messages:
    1. Right-click on the project node, select New->Other->Other->Properties, and click Next.
    2. Enter ApplicationMessages as the file name, src\java\guessNumber as the folder, and click Finish.
    3. Replace the content of the properties file with the ApplicationMessages.properties example code listed above and save the file.
  7. Create two new XHTML pages and name them greeting.xhtml and response.xhtml respectively.
    1. Replace the content of greeting.xhtml with the example code listed above and save the file.
    2. Replace the content of response.xhtml with the example code listed above and save the file.
  8. Create a simple index.html page that redirects the browser client to greeting.xhtml.
  9. Add Duke's image as part of the UI by copying the wave.med.gif image file from the tutorial example and save it in the web folder.
  10. Configure the application resource configuration file by replacing the content of faces-config.xml with the example code listed above.
  11. Configure the web deployment descriptor file by replacing the content of web.xml with the example code listed above.
  12. Configure the sub-web.xml file to modify the welcome page to index.html.
  13. Compile and build the application.
  14. Deploy the application to GlassFish v3 Preview.
  15. Access the application from the browser by entering the URL http://localhost:8080/guessNumber.