猜数字游戏规则:
由Login类的execute方法随机生成一个0-99的数字, 用户进行猜测 。 在web页面实时反馈 数字“过大”,“过小”和“总计猜了多少次”等信息。
首先在welcome-file 中加入起始页面 success.jsp
这个页面用来接收第一次输入的数据:
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>Insert title here</title> </head> <body> 请猜一个数字 <form action="guess/guess" method="post"> 我猜<input type="text" name="number"></input> <input type="submit" value="submit"/> </form> </body> </html>
public class Guess extends ActionSupport implements RequestAware{ private static Integer count=0; private Integer number; private java.util.Random r=new java.util.Random(); private static Integer theone; private Map<String,Object>request; public String execute() { //System.out.println(number); if(count==null) count=0; if(count==0) { request.put("result", "请您猜一个数字吧"); request.put("count", count); theone=Math.abs(r.nextInt()); theone=theone%100; System.out.println("这个数是"+theone); } if (number>theone){ count++; request.put("result", "猜大了哟"); request.put("count", count); } if(number<theone){ count++; request.put("result", "猜的太小了魂淡"); request.put("count", count); } if(number==theone){ count=0; request.put("result", "猜对啦"); request.put("count", count); } System.out.println("本轮一共猜了"+count+"次"); return "success"; } public Integer getNumber(){ return number; } public void setNumber(Integer number){ this.number=number; } @Override public void setRequest(Map<String, Object> request) { // TODO Auto-generated method stub this.request=request; } }
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <%@taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>Insert title here</title> </head> <body> <form action="guess/guess" method="post"> <%= request.getAttribute("result")%> <br /> 您现在共猜了<%= request.getAttribute("count") %>次<br /> 我猜<input type="text" name="number"></input> <input type="submit" value="submit"/> </form> </body> </html>
这是一个基本的struts2小程序,关于request进行通信的简单应用。
原文:http://blog.csdn.net/pandora_madara/article/details/20619339