<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>大富翁猜数字游戏</title>
</head>
<body>
<%
String msg = (String)request.getAttribute("msg");
if(msg!=null){
out.write("<font color='red'>"+msg+"</font>");
}
%>
<%
//获取竞猜次数
Integer times = (Integer)request.getAttribute("times");
if(times!=null){
out.write(",你还有"+(5-times)+"次机会!");
}
%>
<form action="/myday14guess/GuessServlet" method="get">
请输入30以内的整数:<input type="text" name="lucyNo">
<%
if(times!=null){
%>
<input type="hidden" name="times" value="<%=times %>"/>
<%
}
%>
<input type="submit" value="开始竞技">
</form>
</body>
</html>
package gz.itcast.a_exec;
import java.io.IOException;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GuessServlet extends HttpServlet {
int anwer;
public void newGame(){
Random random = new Random();
anwer = random.nextInt(30);
}
public GuessServlet() {
newGame();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//接收数据
String lucyNoStr = request.getParameter("lucyNo");
System.out.println("产生的随机数是:" + anwer);
Integer lucyNo=null;
if(lucyNoStr!=null || !lucyNoStr.equals("")){
lucyNo = Integer.parseInt(lucyNoStr);
}
//当前竞技的次数
Integer times=1;//初始的数值
//接收客户端当前竞猜的次数
String timesStr = request.getParameter("times");
if(timesStr!=null && !timesStr.equals("")){
times = Integer.parseInt(timesStr)+1;
}
if(times<5){
String msg = "";
//比较
if(lucyNo>anwer){
//大了
msg = "可惜,大了点";
}else if(lucyNo<anwer){
//小了
msg = "可惜,小了点";
}else if(lucyNo==anwer){
//等于,中奖
msg = "恭喜你,中得1000000元现金大奖,请带身份证到xxx地方领奖!";
times = null;
}
//把当前竞猜的次数放入域对象
request.setAttribute("times", times);
//把信息放入域对象中
request.setAttribute("msg", msg);
}else{
//产生新的幸运数字
newGame();
//游戏结束
response.getWriter().write("游戏结束。<a href='"+request.getContextPath()+"/guess.jsp'>再来一盘</a>");
return;
}
//转发
request.getRequestDispatcher("/guess.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}