猜数字游戏规则:
由Login类的execute方法随机生成一个0-99的数字, 用户进行猜测 。 在web页面实时反馈 数字“过大”,“过小”和“总计猜了多少次”等信息。
首先在welcome-file 中加入起始页面 success.jsp
这个页面用来接收第一次输入的数据:
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
Insert title here
请猜一个数字
接收到数据后传给guess这个action 。 guess的class代码如下:
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
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
request) { // TODO Auto-generated method stub this.request=request; } }
这里用number来接收jsp中传来的用户输入数字。 同时生成的result和count信息由request传给jsp文件。 这个类return到 name==success的result。 这个result的jsp文件如下所示:
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@taglib prefix="s" uri="/struts-tags" %>
Insert title here
可以看到基本上与success.jsp相同, 在result 和count部分通过request做了替换。
这是一个基本的struts2小程序,关于request进行通信的简单应用。
