猜数字游戏Example
这个例子展示使用了Struts Flow的猜数字游戏的实现。目的是为了展现这个扩展功能的基本概念,所以这个例子保持简单。这个例子基本上有三部分;flow code, the Struts config, 和用来显示输出的JSP。
Flow Code
flow code 如下所示:
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( struts.param.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} );
}
注意程序是如何循环直到数字被猜对,甚至是页被发到浏览器去获得用户的输入。
Struts Configuration
为了用Struts配置这个程序,下面的action mapping和plug-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>
自定义的action mapping中的function
属性告知JavaScript函数的FlowAction
被调用。
JSP Presentation
为了收集用户猜测,guess.jsp
声称一个表单:
<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>隐藏的输入变量contid
存储当表单提交时加载的延续。
原文地址:http://struts.apache.org/struts-flow/guess-example.html