JSP学习案例--,竞猜游戏
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>百万富翁数字竞猜游戏</title> </head> <body> <% //从request域中取出信息 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="/GuessServlet" method="post"> 请输入30以下的整数:<input type="text" name="lucyNo"/><br/> <% if(times!=null){ %> <input type="hidden" name="times" value="<%=times %>"/> <% } %> <input type="submit" value="开始竞猜"/> </form> </body> </html>
package com.loaderman.demo; import javax.servlet.ServletException; import javax.servlet.http.*; import java.io.IOException; import java.util.Random; public class TestServlet extends HttpServlet { //产生一个幸运数字 int answer; /** * 新游戏方法。产生一个新的幸运数字 */ public void newGame(){ Random random = new Random(); answer = random.nextInt(30); } public TestServlet(){ //第一次访问 newGame(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); //1.接收输入的数字 String lucyNoStr = request.getParameter("lucyNo"); System.out.println("答案:"+answer); Integer lucyNo = null; //2.判断幸运数字和用户的数字 //2.1 把用户输入的数字转成整数 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>answer){ //大了 msg = "可惜,大了点"; }else if(lucyNo<answer){ //小了 msg = "可惜,小了点"; }else if(lucyNo==answer){ //等于,中奖 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("/05.guess.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!