Struts Applications
 
   

Struts Flow - Number Guess Example

PDF
PDF

Number Guessing Game Example

This example shows a number guessing game implemented with Struts Flow. The goal is to show the basic concepts of continuations, so the example is kept simple. There are basically three parts to the example: the flow code, the Struts config, and the JSP's that display the output.

Flow Code

Here is what the flow code looks like:

function main() {

  var random =  Math.round( Math.random() * 9 ) + 1;
  var hint = "No hint for you!"
  var guesses = 0;

  while (true) {

    // send guess page to user and wait for response
    forwardAndWait("failure", 
       { "random"  : random, 
         "hint"    : hint,
         "guesses" : guesses} );

    // process user's guess
    var guess = parseInt( getRequestParams().guess );
    guesses++;
    if (guess) {
      if (guess > random) {
        hint = "Nope, lower!"
      } 
      else if (guess < random) {
        hint = "Nope, higher!"
      } 
      else {
        // correct guess
        break;
      }
    }
  }

  // send success page to user
  forwardAndWait("success", 
     {"random"  : random, 
      "guess"   : guess, 
      "guesses" : guesses} );
}

Notice how the program loops until the number is guessed, even though pages are being sent to the browser to gather user input.

Struts Configuration

To configure this application with Struts, the following action mapping and plug-in are defined in struts-config.xml:

<action-mappings>

    <action    path="/guess"
               type="net.sf.struts.flow.FlowAction"
          className="net.sf.struts.flow.FlowMapping">
           
      <set-property property="function"   value="main"/>     
      <forward name="failure"              path="/guess.jsp"/>
      <forward name="success"              path="/success.jsp"/>
    </action>
</action-mappings>   


<plug-in className="net.sf.struts.flow.FlowPlugIn">
    <set-property property="scripts" value="/WEB-INF/numberguess.js" />
</plug-in>

The function property of the custom action mapping tells FlowAction which JavaScript function to call.

JSP Presentation

To gather the user's guess, guess.jsp generates a form:

<html>
<head>
  <title>Struts Flow number guessing game</title>
</head>
<body>

  <h1>Guess the Number Between 1 and 10</h1>
  
  <h2><%= request.getAttribute("hint") %></h2>
  
  <h3>You've guessed <%= request.getAttribute("guesses") %> times.</h3>
  
  <form method="post" action="guess.do">
    <input type="hidden" name="contid" value='<%= request.getAttribute("contid") %>' />
    <input type="text" name="guess"/>
    <input type="submit"/>
  </form>
  
</body>
</html>

The hidden input variable contid stores the continuation to load from when the form gets submitted.