Java Platform, Enterprise Edition (Java EE) 8 The Java EE Tutorial

## The ajaxguessnumber Example Application

To demonstrate the advantages of using Ajax, revisit the `guessnumber` example from Chapter 8, "Introduction to Facelets". If you modify this example to use Ajax, the response need not be displayed on the `response.xhtml` page. Instead, an asynchronous call is made to the bean on the server side, and the response is displayed on the originating page by executing just the input component rather than by form submission.

The source code for this application is in the tut-install`/examples/web/jsf/ajaxguessnumber/` directory.

The following topics are addressed here:

- The ajaxguessnumber Source Files

- Running the ajaxguessnumber Example

### The ajaxguessnumber Source Files

The changes to the `guessnumber` application occur in two source files.

The following topics are addressed here:

- The ajaxgreeting.xhtml Facelets Page

- The UserNumberBean Backing Bean

- The DukesNumberBean CDI Managed Bean

#### The ajaxgreeting.xhtml Facelets Page

The Facelets page for `ajaxguessnumber`, `ajaxgreeting.xhtml`, is almost the same as the `greeting.xhtml` page for the `guessnumber` application:

    <h:head>
        <h:outputStylesheet library="css" name="default.css"/>
        <title>Ajax Guess Number Facelets Application</title>
    </h:head>
    <h:body>
        <h:form id="AjaxGuess">
            <h:graphicImage value="#{resource['images:wave.med.gif']}"
                            alt="Duke waving his hand"/>
            <h2>
                Hi, my name is Duke. I am thinking of a number from
                #{dukesNumberBean.minimum} to #{dukesNumberBean.maximum}.
                Can you guess it?
            </h2>
            <p>
                <h:inputText id="userNo"
                             title="Enter a number from 0 to 10:"
                             value="#{userNumberBean.userNumber}">
                    <f:validateLongRange minimum="#{dukesNumberBean.minimum}"
                                         maximum="#{dukesNumberBean.maximum}"/>
                </h:inputText>

                <h:commandButton id="submit" value="Submit">
                    <f:ajax execute="userNo" render="outputGroup" />
                </h:commandButton>
            </p>
            <p>
                <h:panelGroup layout="block" id="outputGroup">
                    <h:outputText id="result" style="color:blue"
                                  value="#{userNumberBean.response}"
                                  rendered="#{!facesContext.validationFailed}"/>
                    <h:message id="errors1"
                               showSummary="true"
                               showDetail="false"
                               style="color: #d20005;
                               font-family: 'New Century Schoolbook', serif;
                               font-style: oblique;
                               text-decoration: overline"
                               for="userNo"/>
                </h:panelGroup>
            </p>
        </h:form>
    </h:body>

The most important change is in the `h:commandButton` tag. The `action` attribute is removed from the tag, and an `f:ajax` tag is added.

The `f:ajax` tag specifies that when the button is clicked the `h:inputText` component with the `id` value `userNo` is executed. The components within the `outputGroup` panel group are then rendered. If a validation error occurs, the managed bean is not executed, and the validation error message is displayed in the message pane. Otherwise, the result of the guess is rendered in the `result` component.

#### The UserNumberBean Backing Bean

A small change is also made in the `UserNumberBean` code so that the output component does not display any message for the default (null) value of the property `response`. Here is the modified bean code:

    public String getResponse() {
        if ((userNumber != null)
                && (userNumber.compareTo(dukesNumberBean.getRandomInt()) == 0)) {
            return "Yay! You got it!";
        }
        if (userNumber == null) {
            return null;
        } else {
            return "Sorry, " + userNumber + " is incorrect.";
        }
    }

#### The DukesNumberBean CDI Managed Bean

The `DukesNumberBean` session-scoped CDI managed bean stores the range of guessable numbers and the randomly chosen number from that range. It is injected into `UserNumberBean` with the CDI `@Inject` annotation so that the value of the random number can be compared to the number the user submitted:

    @Inject
    DukesNumberBean dukesNumberBean;

You will learn more about CDI in Chapter 25, "Introduction to Contexts and Dependency Injection for Java EE".

### Running the ajaxguessnumber Example

You can use either NetBeans IDE or Maven to build, package, deploy, and run the `ajaxguessnumber` application.

The following topics are addressed here:

- To Build, Package, and Deploy the ajaxguessnumber Example Using NetBeans IDE

- To Build, Package, and Deploy the ajaxguessnumber Example Using Maven

- To Run the ajaxguessnumber Example

#### To Build, Package, and Deploy the ajaxguessnumber Example Using NetBeans IDE

1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server).

2. From the File menu, choose Open Project.

3. In the Open Project dialog box, navigate to:

       tut-install/examples/web/jsf

4. Select the `ajaxguessnumber` folder.

5. Click Open Project.

6. In the Projects tab, right-click the `ajaxguessnumber` project and select Build.

   This command builds and deploys the project.

#### To Build, Package, and Deploy the ajaxguessnumber Example Using Maven

1. Make sure that GlassFish Server has been started (see Starting and Stopping GlassFish Server).

2. In a terminal window, go to:

       tut-install/examples/web/jsf/ajaxguessnumber/

3. Enter the following command:

       mvn install

   This command builds and packages the application into a WAR file, `ajaxguessnumber.war`, located in the `target` directory. It then deploys the application.

#### To Run the ajaxguessnumber Example

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

       http://localhost:8080/ajaxguessnumber

2. Enter a value in the field and click Submit.

   If the value is in the range of 0 to 10, a message states whether the guess is correct or incorrect. If the value is outside that range or if the value is not a number, an error message appears in red.

Copyright © 2017, Oracle and/or its affiliates. All rights reserved.