jsp+servlet实现猜数字游戏主要用到了servlet方面的session,HttpServletResponse类中的sendRedirect()方法。
step1,客户访问或刷新getNumber.jsp页面时,随机给用户分配一个1-100之间的数字,将该数字存放到客户的session中。
<%@ page language="java" import="java.util.*" contentType="text/html;charset=utf-8"%> <html> <head> </head> <body> <% String message=(String)session.getAttribute("message"); %> <form action="HandleGuess" methods="post"> <input type="text" size=8> <%=message %> <input type="submit" value="提交"> </form> <form action="getNumber.jsp" method="post"> <input type="submit" value="重新得到新的随机数"> </form> </body> </html>
step2,然后用户超廉价到inputNumber.jsp页面上,用户输入自己的猜测,并提交给HandleGuess类负责创建。
<%@ page language="java" import="java.util.*" pageEncoding="utf-8" contentType="text/html;Charset=utf-8"%> <html> <head> </head> <body> <% session.setAttribute("message", "请您猜数"); // HttpSession session =request.getSession(true); int randomNumber=(int)(Math.random()*100)+1;//获取一个随机数 session.setAttribute("saveNumber",new Integer(randomNumber)); %> <p>访问或刷新该页面可以随机跌倒一个1,到100之间的数字 <br>单击下面链接可以访问去猜数字 <a href="https://www.jb51.net/inputNumber.jsp" >去猜数字</a> </body> </html>
step3,该servlet类为:
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class HandleGuess extends HttpServlet { public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{ request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out=response.getWriter(); //获取客户猜测提交的数 int guessNumber=Integer.parseInt(request.getParameter("guessnumber")); //获取客户的会话对象 HttpSession session=request.getSession(); Integer integer=(Integer)session.getAttribute("saveNumber"); int realNumber=integer.intValue(); System.out.println(realNumber); System.out.println(guessNumber); if(guessNumber>realNumber){ session.setAttribute("message", "您猜大了"); System.out.println("您猜大了---no"); response.sendRedirect("https://www.jb51.net/inputNumber.jsp"); } else if(guessNumber<realNumber){ session.setAttribute("message", "您猜小了"); System.out.println("您猜小了---no"); response.sendRedirect("https://www.jb51.net/inputNumber.jsp"); } else{ session.setAttribute("message", "您猜对了"); System.out.println("您猜对了"); response.sendRedirect("https://www.jb51.net/inputNumber.jsp"); } } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{ doPost(request,response); } }
step4,web.xml配置,省略。