JSP猜数字游戏

    主要内容:本博客通过设计一个猜数字的游戏来学习jsp的servlet的使用方法。

步骤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>

步骤2:resultServlet的创建

负责判断提交的猜测的数是否和生成的随机数相等,如果相等显示猜对的消息。否则,如果提交的数比较大,跳转到large.jsp中;如果提交的数比较小,跳转到small.jsp中。
resultServlet类继承了HttpServlet,在类中主要编写doGet和doPost函数,并通过doPost函数调用doGet函数,在doGet函数中主要编写判断猜测的数字是否猜对了。编写完servlet类的代码后,还需再xml中配置servlet的访问方式。

  1. 创建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)//猜对了,输出成功信息.
		 		{
		 			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. resultServlet类的访问方式.
    1)再xml配置文件中配置resultServlet的属性,浏览器可以通过url-pattern的内容在目录下访问,具体使用方式可以百度查询。
    在这里插入图片描述

步骤3 创建large.jsp和small.jsp

包含提示信息和表单,表单用来输入继续猜测的数字,仍然时提交给resultServlet。
实现代码如下:

large.jsp:

 <%
	String number=((Integer)session.getAttribute("RNum")).toString();
	String count = ((Integer)session.getAttribute("count")).toString();
	String inum=   request.getParameter("input");
 %>
 <%--测试使用
要猜测的数字<%=number %>.<br>
注:使用转发跳转;
 --%> 
猜了<%=count %>次,
你猜的数字(<%=inum %>)大了,请猜小一些 <br>
<form action="resultServlet" method="post">
	请输入你猜测的数字:<input type="text" name="input" size="5">
	<input type="submit" value="提交">
</form>

small.jsp

<%
	String number=((Integer)session.getAttribute("RNum")).toString();
	String count = ((Integer)session.getAttribute("count")).toString();
	String inum=   request.getParameter("input");
%>
<%--测试使用
要猜测的数字<%=number %>.<br>
注:使用重定向跳转;
--%> 
猜了<%=count %>次,
  你猜的数字(<%=inum %>)小了,请猜大一些 <br>
<form action="resultServlet" method="post">
	请输入你猜测的数字:<input type="text" name="input" size="5">
	<input type="submit" value="提交">
</form>

步骤4结果展示

  1. 初始界面
    在这里插入图片描述
  2. 输入后提交
    在这里插入图片描述
  3. 再输入提交
    在这里插入图片描述
  4. 猜对了
    在这里插入图片描述

学习反思

通过使用servlet来实现jsp页面提交的数据的处理,并发生页面的重定向或者转发实现跳转。再使用的过程中用到了session对象,为每个用户创建的,可以保存属性的对象。serlvet的使用要多注意其中的方式步骤,否则会容易出错。

注:写的博客比较少,可能问题比较多,欢迎留言指出。
代码参考:
https://pan.baidu.com/s/1LJMB8WFrEWfh8byifrP8nA

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐