該猜數字遊戲主要用到了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" name="guessnumber" 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="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("inputNumber.jsp"); } else if(guessNumber<realNumber){ session.setAttribute("message", "您猜小了"); System.out.println("您猜小了---no"); response.sendRedirect("inputNumber.jsp"); } else{ session.setAttribute("message", "您猜對了"); System.out.println("您猜對了"); response.sendRedirect("inputNumber.jsp"); } } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{ doPost(request,response); } }
step4,web.xml配置,省略。