The Java EE 6 Tutorial, Volume I

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" 
<html xmlns=""
    <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> 
                <h:panelGrid border="0" columns="5" style="font-size: 18px;">
                    <h:inputText id="inputGuess"
                       required="true" size="3"
                       disabled="#{userNumberBean.number eq userNumberBean.userNumber}"
                    <h:commandButton id="GuessButton" value="Guess"
                       disabled="#{userNumberBean.number eq userNumberBean.userNumber}"/>
                    <h:commandButton id="RestartButton" value="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"/>
                <div style="color: red; font-size: 14px;">
                    <h:messages id="messages" globalOnly="false"/>

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.