本任务编写一个Servlet实现猜骰子大小游戏。使用HttpSession对象存储随机数,当使用GET请求访问它时,生成一个1~6之间的随机整数,将其作为一个属性存储到用户的会话对象中,同时提供一个表单供用户输入猜测的“大”or“小”。如果该Servlet接收到一个POST请求,它将比较用户猜的大小和随机生成的数是否符合条件,给出结果,并允许用户重新猜。
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
@WebServlet("/guess-number")
public class GuessNumberServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public GuessNumberServlet() {
super();
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int magic=(int)(Math.random()*6+1);//生成一个1~6之间的随机整数
HttpSession session=request.getSession();
session.setAttribute("num", new Integer(magic));
response.setContentType("text/html;charset=UTF-8");
PrintWriter out=response.getWriter();
out.println("<html><body>");
out.println("一个骰子,通常有6种点数。我们将1、2、3记作“小”,将4、5、6记作“大”。我投一个点,你来猜“小”了还是“大”了。");
out.println("<form action='guess-number' method='post'>");
out.println("<input type='text' name='guess'/>");
out.println("<input type='submit' value='确定'/>");
out.println("</form>");
out.println("</body></html>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String guess=request.getParameter("guess");//得到输入的值
byte [] bytes =guess.getBytes("ISO-8859-1");
guess= new String(bytes, "utf-8");
HttpSession session=request.getSession();
int magic=(Integer)session.getAttribute("num");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out=response.getWriter();
out.println("<html><body>");
if(guess.equals("大")&&magic>3) {
session.invalidate();//销毁对话
out.println("祝贺你,猜对了!");
out.println("<a href='guess-number'>再猜一次</a>"); //返回猜界面,重新随机一个数
}
else if(guess.equals("小")&&magic<4) {
out.println("祝贺你,猜对了!");
out.println("<a href='guess-number'>再猜一次</a>"); //返回猜界面,重新随机一个数
}
else {
out.println("猜错了,请重猜");
}
out.println("<form action='guess-number' method='post>");
out.println("<input type='text' name='guess'/>");
out.println("<input type='submit' value='确定'/>");
out.println("</form>");
out.println("</body></html>");
}
}
运行结果: