JSP猜數字游戲


JSP猜數字游戲
主要內容:本博客通過設計一個猜數字的游戲來學習jsp的servlet的使用方法。
1
步驟1:創建inputGuess.jsp
用戶請求這個頁面是,頁面會給用戶生成一個1–100的隨機數。這個頁面提供表單,用來提交用戶猜測的數字,並提交給resultServlet處理。
實現的主要代碼:

<%
int number = (int)(Math.random()*100)+1;//生成一個隨機數;
session.setAttribute("count", new Integer(0));//將統計猜測的次數保存在session中
session.setAttribute("RNum", new Integer(number));//將隨機數存在session中.
%>
<p>猜數字游戲(數字范圍1-100)</p>
<form action="resultServlet" method="post">
請輸入你猜測的數字:<input type="text" name="input" size="5" >
<input type="submit" value="提交">
</form>
1
2
3
4
5
6
7
8
9
10
步驟2:resultServlet的創建
負責判斷提交的猜測的數是否和生成的隨機數相等,如果相等顯示猜對的消息。否則,如果提交的數比較大,跳轉到large.jsp中;如果提交的數比較小,跳轉到small.jsp中。
resultServlet類繼承了HttpServlet,在類中主要編寫doGet和doPost函數,並通過doPost函數調用doGet函數,在doGet函數中主要編寫判斷猜測的數字是否猜對了。編寫完servlet類的代碼后,還需再xml中配置servlet的訪問方式。

創建servlet的關鍵代碼:
public class ResultServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("gb2312");//設置請求和回復的編碼方式;
req.setCharacterEncoding("gb2312");
String str = req.getParameter("input");//獲取猜測的數字;
HttpSession session = req.getSession();//獲取session對象;
try{
int cNum = Integer.parseInt(str);
int count= ((Integer)session.getAttribute("count")).intValue();//從session對象中獲取屬性值,獲取猜測的次數;
int RNum = ((Integer)session.getAttribute("RNum")).intValue();//獲取生成的隨機數.
if(cNum<=0||cNum>100)//輸入錯誤,返回到初始頁;
{
resp.sendRedirect("inputGuess.jsp");
}
if(cNum==RNum)//猜對了,輸出成功信息.
{(http://www.amjmh.com)
count=count+1;
session.setAttribute("count", new Integer(count));
resp.setContentType("text/html;charset=gb2312");
PrintWriter out = resp.getWriter();//創建輸出對象;
out.println("<html><body bgcolor=cyan>");
out.println("猜對了,正確的數是:"+RNum);
out.println("<br>一共猜了"+count+"次");
out.println("</body></html>");
}
else
if(cNum<=RNum)//猜的數字比較小.
{
count=count+1;
session.setAttribute("count", new Integer(count));
//RequestDispatcher dispa=req.getRequestDispatcher("small.jsp");
//dispa.forward(req, resp);
resp.sendRedirect("small.jsp");//重定向,不傳遞提交的數據
}
else
if(cNum>RNum)猜的數字比較大.
{
count=count+1;
session.setAttribute("count", new Integer(count));
RequestDispatcher dispa=req.getRequestDispatcher("large.jsp");//轉發可以傳遞提交的數據;
dispa.forward(req, resp);
//resp.sendRedirect("large.jsp");
}
}catch(NumberFormatException e)
{
resp.sendRedirect("inputGuess.jsp");//出現異常,跳轉到默認頁面.
}

}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);//調用deGet。
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
resultServlet類的訪問方式.
1)再xml配置文件中配置resultServlet的屬性,瀏覽器可以通過url-pattern的內容在目錄下訪問,具體使用方式可以百度查詢。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM