type=page
status=published
title=The ajaxguessnumber Example Application
next=jsf-ajax012.html
prev=jsf-ajax010.html
~~~~~~
= The ajaxguessnumber Example Application


[[GKOKB]]

[[the-ajaxguessnumber-example-application]]
The ajaxguessnumber Example Application
---------------------------------------

To demonstrate the advantages of using Ajax, revisit the `guessnumber`
example from link:jsf-facelets.html#GIEPX[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:

* link:#GKOIJ[The ajaxguessnumber Source Files]
* link:#GKOKE[Running the ajaxguessnumber Example]

[[GKOIJ]]

[[the-ajaxguessnumber-source-files]]
The ajaxguessnumber Source Files
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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

The following topics are addressed here:

* link:#GKOFW[The ajaxgreeting.xhtml Facelets Page]
* link:#GKOHN[The UserNumberBean Backing Bean]
* link:#CHDGAIGJ[The DukesNumberBean CDI Managed Bean]

[[GKOFW]]

[[the-ajaxgreeting.xhtml-facelets-page]]
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:

[source,oac_no_warn]
----
<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.

[[GKOHN]]

[[the-usernumberbean-backing-bean]]
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:

[source,oac_no_warn]
----
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.";
    }
}
----

[[CHDGAIGJ]]

[[the-dukesnumberbean-cdi-managed-bean]]
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:

[source,oac_no_warn]
----
@Inject
DukesNumberBean dukesNumberBean;
----

You will learn more about CDI in link:cdi-basic.html#GIWHB[Chapter 25,
"Introduction to Contexts and Dependency Injection for Java EE"].

[[GKOKE]]

[[running-the-ajaxguessnumber-example]]
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:

* link:#GLHVU[To Build, Package, and Deploy the ajaxguessnumber Example
Using NetBeans IDE]
* link:#GLHVQ[To Build, Package, and Deploy the ajaxguessnumber Example
Using Maven]
* link:#GLHWE[To Run the ajaxguessnumber Example]

[[GLHVU]]

[[to-build-package-and-deploy-the-ajaxguessnumber-example-using-netbeans-ide]]
To Build, Package, and Deploy the ajaxguessnumber Example Using NetBeans IDE
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

1.  Make sure that GlassFish Server has been started (see
link:usingexamples002.html#BNADI[Starting and Stopping GlassFish
Server]).
2.  From the File menu, choose Open Project.
3.  In the Open Project dialog box, navigate to:
+
[source,oac_no_warn]
----
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.

[[GLHVQ]]

[[to-build-package-and-deploy-the-ajaxguessnumber-example-using-maven]]
To Build, Package, and Deploy the ajaxguessnumber Example Using Maven
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

1.  Make sure that GlassFish Server has been started (see
link:usingexamples002.html#BNADI[Starting and Stopping GlassFish
Server]).
2.  In a terminal window, go to:
+
[source,oac_no_warn]
----
tut-install/examples/web/jsf/ajaxguessnumber/
----
3.  Enter the following command:
+
[source,oac_no_warn]
----
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.

[[GLHWE]]

[[to-run-the-ajaxguessnumber-example]]
To Run the ajaxguessnumber Example
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

1.  In a web browser, enter the following URL:
+
[source,oac_no_warn]
----
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.
