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的内容在目录下访问,具体使用方式可以百度查询。

 

posted @ 2019-10-12 13:41  李艳艳665  阅读(1500)  评论(0编辑  收藏  举报