The Java EE 6 Tutorial, Volume I

Part V Contexts and Dependency Injection for the JavaTM EE Platform

Part Five explores Contexts and Dependency Injection for the Java EE Platform.

Chapter 17 Introduction to Contexts and Dependency Injection for the JavaTM EE Platform

Contexts and Dependency Injection for the Java EE Platform (CDI) is one of several Java EE 6 features that help to knit together the web tier and the transactional tier of the Java EE platform. It is a set of services that, used together, makes it easy for developers to use enterprise beans along with JavaServerTM Faces technology in web applications. Designed for use with stateful objects, it also has many broader uses, allowing developers a great deal of flexibility to integrate different kinds of components in a loosely coupled but type-safe way.

CDI is specified by JSR-299, which was formerly known as Web Beans. Related specifications that CDI uses include the following:

This chapter covers the following topics.

Overview of Contexts and Dependency Injection for the Java EE Platform

The two most fundamental services provided by CDI are as follows:

In addition, CDI provides the following services:

A major theme of CDI is loose coupling. CDI does the following:

Along with loose coupling, CDI provides strong typing, as follows:

About Beans

CDI redefines the concept of a bean beyond its use in other Java technologies, such as the JavaBeansTM and Enterprise JavaBeansTM (EJBTM) technologies. In CDI, a bean is a source of contextual objects that defines application state and/or logic. A Java EE component is a bean if the lifecycle of its instances may be managed by the container according to the lifecycle context model defined in the CDI specification.

More specifically, a bean has the following attributes:

A bean type defines a client-visible type of the bean. Almost any Java type may be a bean type of a bean:

About Managed Beans

A managed bean is a bean that is implemented by a Java class, which is called its bean class. A top-level Java class is a managed bean if it is defined to be a managed bean by any other Java EE technology specification (for example, the JavaServer Faces technology specification), or if it meets all of the following conditions:

No special declaration, such as an annotation, is required to define a managed bean.

Beans as Injectable Objects

The concept of injection has been part of Java technology for some time. Since the Java EE 5 platform was introduced, annotations have made it possible to inject resources and some other kinds of objects into container-managed objects. CDI makes it possible to inject more kinds of objects, and to inject them into objects that are not container-managed.

The following kinds of objects can be injected:

For example, suppose you created a simple Java class with a method that returns a string:

package greetings;

public class Greeting {
    public String greet(String name) {
        return "Hello, " + name + ".";
    }
}

This class becomes a bean that you can then inject into another class. This bean is not exposed to the EL in this form. Giving Beans EL Names explains how you can make a bean accessible via the EL.

Using Qualifiers

You can use qualifiers to provide different implementations of a particular bean type. A qualifier is an annotation that you apply to a bean. A qualifier type is a Java annotation defined as @Target({METHOD, FIELD, PARAMETER, TYPE}) and @Retention(RUNTIME).

For example, you could declare an @Informal qualifier type and apply it to another class that extends the Greeting class. To declare this qualifier type, you would use the following code:

package greetings;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.inject.Qualifier;

@Qualifier
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
public @interface Informal {}

You can then define a bean class that extends the Greeting class and uses this qualifier:

package greetings;

@Informal
public class InformalGreeting extends Greeting {
    public String greet(String name) {
        return "Hi, " + name + "!";
    }
}

Both implementations of the bean can now be used in the application.

If you define a bean with no qualifier, it automatically has the qualifier @Default. The unannotated Greeting class could be declared as follows:

package greetings;

import javax.enterprise.inject.Default;

@Default
public class Greeting {
    public String greet(String name) {
        return "Hello, " + name + ".";
    }
}

Injecting Beans

In order to use the beans you create, you inject them into yet another bean that can then be used by an application, such as a JavaServer Faces application. For example, you might create a bean called Printer into which you would inject one of the Greeting beans:

import javax.inject.Inject;

public class Printer {

    @Inject Greeting greeting;
    ...

This code injects the @Default Greeting implementation into the bean, while the following code injects the @Informal implementation:

import javax.inject.Inject;

public class Printer {

    @Inject @Informal Greeting greeting;
    ...

More is needed for the complete picture of this bean. Its use of scope needs to be understood. In addition, for a JavaServer Faces application, the bean needs to be accessible through the unified expression language (unified EL).

Using Scopes

For a web application to use a bean that injects another bean class, the bean needs to be able to hold state over the duration of the user's interaction with the application. The way to define this state is to give the bean a scope. You can give an object any of the scopes described in Table 17–1, depending on how you are using it.

Table 17–1 Scopes

Scope 

Annotation 

Duration 

Request scope 

@RequestScoped

A user's interaction with a web application in a single HTTP request 

Session scope 

@SessionScoped

A user's interaction with a web application across multiple HTTP requests 

Application scope 

@ApplicationScoped

Shared state across all users' interactions with a web application 

Dependent scope 

@Dependent

The default scope if none is specified; it means that an object exists to serve exactly one client (bean), and has the same lifecycle as that client (bean) 

Conversation scope 

@ConversationScoped

A user's interaction with a JavaServer Faces application, within explicit boundaries controlled by the developer that extend the scope across multiple invocations of the JavaServer Faces life cycle. All long-running conversations are scoped to a particular HTTP servlet session and may not cross session boundaries. 

The first three scopes were originally defined by the Java Servlet specification. The last two are defined by JSR-299.

You can also define and implement custom scopes, but that is an advanced topic. Custom scopes are likely to be used by those who implement and extend the CDI specification.

A scope gives an object a well-defined lifecycle context. A scoped object can be automatically created when it is needed and automatically destroyed when the context in which it was created ends. Moreover, its state is automatically shared by any clients that execute in the same context.

JavaBeans components, and Java EE components such as servlets and enterprise beans, do not by definition have a well-defined scope. These components are either:

If, however, you create a Java EE component that is a managed bean, it becomes a scoped object, which exists in a well-defined lifecycle context.

The web application for the Printer bean will use a simple request and response mechanism, so the managed bean can be annotated as follows:

import javax.inject.Inject;
import javax.enterprise.context.RequestScoped;

@RequestScoped
public class Printer {

       @Inject @Informal Greeting greeting;
    ...

Beans that use session, application, or conversation scope must be serializable, but beans that use request scope do not have to be serializable.

Giving Beans EL Names

To make a bean accessible through the unified expression language (EL), use the @Named built-in qualifier.

import javax.inject.Inject;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;

@Named
@RequestScoped
public class Printer {

    @Inject @Informal Greeting greeting;
    ...

The @Named qualifier allows you to access the bean using the bean name, with the first letter in lowercase. For example, a Facelets page would refer to the bean as printer.

You can specify an argument to the @Named qualifier to use a non-default name:

@Named("MyPrinter")

With this annotation, the Facelets page would refer to the bean as MyPrinter.

Adding Setter and Getter Methods

To make the state of the managed bean accessible, you need to add setter and getter methods for that state. The createSalutation method calls the bean's greet method, and the getSalutation method retrieves the result.

Once the setter and getter methods have been added, the bean is complete. The final code looks like this:

package greetings;

import javax.inject.Inject;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;

@Named
@RequestScoped
public class Printer {

    @Inject @Informal Greeting greeting;
    
    private String name;
    private String salutation;

    public void createSalutation() {
        this.salutation = greeting.greet(name);
    }

    public String getSalutation() {
        return salutation;
    }
    public String setName(String name) {
       this.name = name;
    }

    public String getName() {
       return name;
    }
}

Using a Managed Bean in a Facelets Page

To use the managed bean in a Facelets page, you typically create a form that uses user interface elements to call its methods and display their results. This example provides a button that asks the user to type a name, retrieves the salutation, then displays the text in a paragraph below the button:

<h:form id="greetme">
   <p><h:outputLabel value="Enter your name: " for="name"/>
      <h:inputText id="name" value="#{printer.name}"/></p>
   <p><h:commandButton value="Say Hello" action="#{printer.createSalutation}"/></p>
   <p><h:outputText value="#{printer.salutation}"/></p>
</h:form>

Injecting Objects by Using Producer Methods

Producer methods provide a way to inject objects that are not beans, objects whose values may vary at run time, and objects that require custom initialization.

For example, if you want to initialize a numeric value defined by a qualifier named @MaxNumber, you can define the value in a managed bean and then define a producer method, getMaxNumber, for it:

    private int maxNumber = 100;
    ...
    @Produces @MaxNumber int getMaxNumber() {
        return maxNumber;
    }

When you inject the object in another managed bean, the container automatically invokes the producer method, initializing the value to 100:

    @Inject @MaxNumber private int maxNumber;

If the value can vary at run time, the process is slightly different. For example, the following code defines a producer method that generates a random number defined by a qualifier called @Random:

    private java.util.Random random = 
        new java.util.Random( System.currentTimeMillis() );

    java.util.Random getRandom() {
        return random;
    }

    @Produces @Random int next() {
        return getRandom().nextInt(maxNumber);
    }

When you inject this object in another managed bean, you declare a contextual instance of the object:

    @Inject @Random Instance<Integer> randomInt;

You then call the get method of the Instance:

this.number = randomInt.get();

Configuring a CDI Application

An application that uses CDI must have a file named beans.xml. The file can be completely empty (it has content only in certain limited situations), but it must be present. For a web application, the beans.xml file can be in either the WEB-INF directory or the WEB-INF/classes/META-INF directory. For EJB modules or JAR files, the beans.xml file must be in the META-INF directory.

Further Information

For more information about Contexts and Dependency Injection for the Java EE Platform, see:

Chapter 18 Running the Basic Contexts and Dependency Injection Examples

This chapter describes in detail how to build and run simple examples that use Contexts and Dependency Injection for the JavaTM EE Platform (CDI).

The examples are in the following directory:

tut-install/examples/cdi/

    To build and run the examples, you will do the following:

  1. Use NetBeans IDE or the Ant tool to compile and package the example.

  2. Use NetBeans IDE or the Ant tool to deploy the example.

  3. Run the example in a web browser.

Each example has a build.xml file that refers to files in the following directory:

tut-install/examples/bp-project/

See Chapter 2, Using the Tutorial Examples, for basic information on installing, building, and running the examples.

The simplegreeting Example

The simplegreeting example illustrates some of the most basic features of CDI: scopes, qualifiers, bean injection, and accessing a managed bean in a JavaServerTM Faces application.

When you run the example, you click a button that presents either a formal or an informal greeting, depending on how you edited one of the classes.

The example includes four source files, a Facelets page and template, and configuration files.

The simplegreeting Source Files

The four source files for the simplegreeting example include the following:

The source files are located in the following directory:

tut-install/examples/cdi/simplegreeting/src/java/greetings

The Facelets Template and Page

To use the managed bean in a simple Facelets application, you can use a very simple template file and index.xhtml page.

The template page, template.xhtml, looks like this:

<?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:h="http://java.sun.com/jsf/html"
      xmlns:ui="http://java.sun.com/jsf/facelets">
    <h:head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <link href="resources/css/default.css" rel="stylesheet" type="text/css"/>
        <title><ui:insert name="title">Default Title</ui:insert></title>
    </h:head>

    <body>
        <div id="container">
            <div id="header">
                <h2><ui:insert name="head">Head</ui:insert></h2>
            </div>

            <div id="space">
                <p></p>
            </div>

            <div id="content">
                <ui:insert name="content"/>
            </div>
        </div>
    </body>
</html>

To create the Facelets page, you can redefine the title and head, then add a small form to the content:

<?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:ui="http://java.sun.com/jsf/facelets"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <ui:composition template="/template.xhtml">

        <ui:define name="title">Simple Greeting</ui:define>
        <ui:define name="head">Simple Greeting</ui:define>
        <ui:define name="content">
            <h:form id="greetme">
               <p><h:outputLabel value="Enter your name: " for="name"/>
                  <h:inputText id="name" value="#{printer.name}"/></p>
               <p><h:commandButton value="Say Hello" action="#{printer.createSalutation}"/></p>
               <p><h:outputText value="#{printer.salutation}"/> </p>
            </h:form>
        </ui:define>

    </ui:composition>
</html>

The form asks the user to type a name. The button is labeled “Say Hello,” and the action defined for it is to call the createSalutation method of the Printer managed bean. This method in turn calls the greet method of the defined Greeting class.

The output text for the form is the value of the greeting returned by the setter method. Depending on whether the default or the @Informal version of the greeting is injected, this is either


Hello, name.

or


Hi, name!

where name is the name typed by the user.

The Facelets page and template are located in the following directory:

tut-install/examples/cdi/simplegreeting/web

The simple CSS file that is used by the Facelets page is in the following location:

tut-install/examples/cdi/simplegreeting/web/resources/css/default.css

Configuration Files

You must create an empty beans.xml file to indicate to Sun GlassFishTM Enterprise Server v3 that your application is a CDI application. This file can have content in some situations, but not in simple applications like this one.

Your application also needs the basic web application deployment descriptors web.xml and sun-web.xml.

These configuration files are located in the following directory:

tut-install/examples/cdi/simplegreeting/web/WEB-INF

Building, Packaging, Deploying, and Running the simplegreeting Example

You can build, package, deploy, and run the simplegreeting application using either NetBeans IDE or the Ant tool.

ProcedureBuilding and Deploying the simplegreeting Example Using NetBeans IDE

Follow these instructions to build, package, and deploy the simplegreeting example to the Enterprise Server using NetBeans IDE.

This procedure builds the application into the tut-install/examples/cdi/simplegreeting/build/web directory and deploys the contents of this directory to the Enterprise Server.

  1. In NetBeans IDE, select File->Open Project.

  2. In the Open Project dialog, navigate to tut-install/examples/cdi/.

  3. Select the simplegreeting folder.

  4. Select the Open as Main Project checkbox.

  5. Click Open Project Folder.

  6. (Optional) To modify the Printer.java file, perform these steps:

    1. Expand the Source Packages node.

    2. Expand the greetings node.

    3. Double-click the Printer.java file.

    4. In the edit pane, comment out the @Informal annotation:

          //@Informal
          @Inject
          Greeting greeting;
    5. Save the file.

  7. In the Projects tab, right-click the simplegreeting project and select Deploy.

ProcedureBuilding, Packaging, and Deploying the simplegreetingExample Using Ant

Follow these instructions to build, package, and deploy the simplegreeting example to the Enterprise Server using Ant.

This procedure builds the application into the tut-install/examples/cdi/simplegreeting/build/web directory and deploys the contents of this directory to the Enterprise Server.

This procedure builds and packages the application into simplegreeting.war, located in tut-install/examples/cdi/simplegreeting/dist/, and deploys this WAR file to the Enterprise Server.

  1. In a terminal window, go to this directory:


    tut-install/examples/cdi/simplegreeting/
  2. Type the following command:


    ant
    

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

  3. Type the following command:


    ant deploy
    

    simplegreeting.war will be deployed to the Enterprise Server.

ProcedureRunning the simplegreeting Example

  1. In a web browser, type the following URL:


    http://localhost:8080/simplegreeting

    The Simple Greeting page opens.

  2. Type a name in the text field.

    For example, suppose you type Duke.

  3. Click the Say Hello button.

    If you did not modify the Printer.java file, the following text string appears below the button:


    Hi, Duke!

    If you commented out the @Informal annotation in the Printer.java file, the following text string appears below the button:


    Hello, Duke.

    Figure 18–1 shows what the application looks like if you did not modify the Printer.java file.

    Figure 18–1 Simple Greeting Application

    Simple Greeting application

The guessnumber Example

The guessnumber example is somewhat more complex than the simplegreeting example. It illustrates the use of producer methods and of session and application scope.

The example is a game in which you try to guess a number in fewer than 10 attempts. It is similar to the guessNumber example described in Chapter 5, Introduction to Facelets, except that you can keep guessing until you get the right answer or until you use up your 10 attempts.

The example includes four source files, a Facelets page and template, and configuration files. The configuration files and the template are the same as those used for the simplegreeting example.

The guessnumber Source Files

The four source files for the guessnumber example include the following:

The source files are located in the following directory:

tut-install/examples/cdi/guessnumber/src/java/guessnumber

The @MaxNumber and @Random Qualifier Interfaces

The @MaxNumber qualifier interface is defined as follows.

package guessnumber;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.inject.Qualifier;

@Target( { TYPE, METHOD, PARAMETER, FIELD })
@Retention(RUNTIME)
@Documented
@Qualifier
public @interface MaxNumber {

}

The @Random qualifier interface is defined as follows.

package guessnumber;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.inject.Qualifier;

@Target( { TYPE, METHOD, PARAMETER, FIELD })
@Retention(RUNTIME)
@Documented
@Qualifier
public @interface Random {

}

The Generator Managed Bean

The Generator managed bean contains the two producer methods for the application. The bean has the @ApplicationScoped annotation to specify that its context extends for the duration of the user's interaction with the application.

package guessnumber;

import java.io.Serializable;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;

@ApplicationScoped
public class Generator implements Serializable {

    private static final long serialVersionUID = -7213673465118041882L;

    private java.util.Random random = 
        new java.util.Random( System.currentTimeMillis() );

    private int maxNumber = 100;

    java.util.Random getRandom() {
        return random;
    }

    @Produces @Random int next() {
        return getRandom().nextInt(maxNumber);
    }

    @Produces @MaxNumber int getMaxNumber() {
        return maxNumber;
    }

}

The UserNumberBean Managed Bean

The UserNumberBean managed bean, the backing bean for the JavaServer Faces application, provides the basic logic for the game. It implements setter and getter methods for the bean fields and injects the two qualifier objects. It provides a reset method that allows you to begin a new game after you complete one. It also provides a check method that determines whether the user has guessed the number, and a validateNumberRange method that determines whether the user's input is correct.

package guessnumber;

import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import javax.inject.Named;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;

@Named
@SessionScoped
public class UserNumberBean implements Serializable {

    private static final long serialVersionUID = 1L;
    private int number;
    private Integer userNumber;
    private int minimum;
    private int remainingGuesses;

    @MaxNumber
    @Inject
    private int maxNumber;

    private int maximum;

    @Random
    @Inject
    Instance<Integer> randomInt;

    public UserNumberBean() {
    }

    public int getNumber() {
        return number;
    }

    public void setUserNumber(Integer user_number) {
        userNumber = user_number;
    }

    public Integer getUserNumber() {
        return userNumber;
    }

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

    public int getRemainingGuesses() {
        return remainingGuesses;
    }

    public String check() throws InterruptedException {
        if (userNumber > number) {
            maximum = userNumber - 1;
        }
        if (userNumber < number) {
            minimum = userNumber + 1;
        }
        if (userNumber == number) {
            FacesContext.getCurrentInstance().addMessage(null, 
                new FacesMessage("Correct!"));
        }
        remainingGuesses--;
        return null;
    }

    @PostConstruct
    public void reset() {
        this.minimum = 0;
        this.userNumber = 0;
        this.remainingGuesses = 10;
        this.maximum = maxNumber;
        this.number = randomInt.get();
    }

    public void validateNumberRange(FacesContext context, UIComponent toValidate, 
                                    Object value) {
        if (remainingGuesses <= 0) {
            FacesMessage message = new FacesMessage("No guesses left!");
            context.addMessage(toValidate.getClientId(context), message);
            ((UIInput) toValidate).setValid(false);
            return;
        }
        int input = (Integer) value;

        if (input < minimum || input > maximum) {
            ((UIInput) toValidate).setValid(false);

            FacesMessage message = new FacesMessage("Invalid guess");
            context.addMessage(toValidate.getClientId(context), message);
        }
    }
}

The Facelets Page

This example uses the same template that the simplegreeting example uses. The index.xhtml file, however, is more complex.

<?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:ui="http://java.sun.com/jsf/facelets"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <ui:composition template="/template.xhtml">

        <ui:define name="title">Guess My Number</ui:define>
        <ui:define name="head">Guess My Number</ui:define>
        <ui:define name="content">
            <h:form id="GuessMain">
                <div style="color: black; font-size: 24px;">
                    <p>I'm thinking of a number between
                    <span style="color: blue">#{userNumberBean.minimum}</span> and 
                    <span style="color: blue">#{userNumberBean.maximum}</span>. You have 
                    <span style="color: blue">#{userNumberBean.remainingGuesses}</span> 
                    guesses.</p>
                </div>
                <h:panelGrid border="0" columns="5" style="font-size: 18px;">
                    Number:
                    <h:inputText id="inputGuess"
                       value="#{userNumberBean.userNumber}"
                       required="true" size="3"
                       disabled="#{userNumberBean.number eq userNumberBean.userNumber}"
                       validator="#{userNumberBean.validateNumberRange}">
                    </h:inputText>
                    <h:commandButton id="GuessButton" value="Guess"
                       action="#{userNumberBean.check}"
                       disabled="#{userNumberBean.number eq userNumberBean.userNumber}"/>
                    <h:commandButton id="RestartButton" value="Reset"
                       action="#{userNumberBean.reset}"
                       immediate="true" />
                    <h:outputText id="Higher" value="Higher!"
rendered="#{userNumberBean.number gt userNumberBean.userNumber and userNumberBean.userNumber ne 0}"
                       style="color: red"/>
                    <h:outputText id="Lower" value="Lower!"
rendered="#{userNumberBean.number lt userNumberBean.userNumber and userNumberBean.userNumber ne 0}"
                       style="color: red"/>
                </h:panelGrid>
                <div style="color: red; font-size: 14px;">
                    <h:messages id="messages" globalOnly="false"/>
                </div>
            </h:form>
        </ui:define>
        
    </ui:composition>
</html>

The Facelets page presents the user with the minimum and maximum values and the number of guesses remaining. The user's interaction with the game takes place within the panelGrid table, which contains an input field, Guess and Reset buttons, and a text field that appears if the guess is higher or lower than the correct number. Every time the user clicks the Guess button, the userNumberBean.check method is called to reset the maximum or minimum value or, if the guess is correct, to generate a FacesMessage to that effect. The userNumberBean.validateNumberRange method determines whether each guess is valid.

Building, Packaging, Deploying, and Running the guessnumber Example

You can build, package, deploy, and run the guessnumber application using either NetBeans IDE or the Ant tool.

ProcedureBuilding and Deploying the guessnumber Example Using NetBeans IDE

Follow these instructions to build, package, and deploy the guessnumber example to the Enterprise Server using NetBeans IDE.

This procedure builds the application into the tut-install/examples/cdi/guessnumber/build/web directory and deploys the contents of this directory to the Enterprise Server.

  1. In NetBeans IDE, select File->Open Project.

  2. In the Open Project dialog, navigate to tut-install/examples/cdi/.

  3. Select the guessnumber folder.

  4. Select the Open as Main Project checkbox.

  5. Click Open Project Folder.

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

ProcedureBuilding, Packaging, and Deploying the guessnumber Example Using Ant

Follow these instructions to build, package, and deploy the guessnumber example to the Enterprise Server using Ant.

This procedure builds the application into the tut-install/examples/cdi/guessnumber/build/web directory and deploys the contents of this directory to the Enterprise Server.

This procedure builds and packages the application into guessnumber.war, located in tut-install/examples/cdi/guessnumber/dist/, and deploys this WAR file to the Enterprise Server.

  1. In a terminal window, go to this directory:


    tut-install/examples/cdi/guessnumber/
  2. Type the following command:


    ant
    

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

  3. Type the following command:


    ant deploy
    

    The guessnumber.war file will be deployed to the Enterprise Server.

ProcedureRunning the guessnumber Example

  1. In a web browser, type the following URL:


    http://localhost:8080/guessnumber

    The Guess My Number page opens, as shown in Figure 18–2.

    Figure 18–2 Guess My Number Example

    Guess Number example at beginning of game

  2. Type a number in the Number text field, then click Guess.

    The minimum and maximum values are modified, along with the remaining number of guesses.

  3. Keep guessing numbers until you get the right answer or run out of guesses.

    If you get the right answer, the input field and Guess button are grayed out, as shown in Figure 18–3.

    Figure 18–3 Guess My Number at End of Game

    Guess Number example at end of game

  4. Click the Reset button to play the game again with a new random number.