设为首页 加入收藏

TOP

struts2实现猜数字游戏
2014-11-24 01:42:57 来源: 作者: 【 】 浏览:0
Tags:struts2 实现 数字 游戏

猜数字游戏规则:

由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




  
<%= request.getAttribute("result")%>
您现在共猜了<%= request.getAttribute("count") %>次
我猜

可以看到基本上与success.jsp相同, 在result 和count部分通过request做了替换。


这是一个基本的struts2小程序,关于request进行通信的简单应用。


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇finally块中不能使用的函数 下一篇数据类型不匹配引起的bug

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: