Struts Applications

Struts Flow - Number Guess Example


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
       { "random"  : random, 
         "hint"    : hint,
         "guesses" : guesses} );

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

  // send success page to user
     {"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    path="/guess"
      <set-property property="function"   value="main"/>     
      <forward name="failure"              path="/guess.jsp"/>
      <forward name="success"              path="/success.jsp"/>

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

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:

  <title>Struts Flow number guessing game</title>

  <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="">
    <input type="hidden" name="contid" value='<%= request.getAttribute("contid") %>' />
    <input type="text" name="guess"/>
    <input type="submit"/>

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