设计一个web app,每次发生一个30以内的数字,给5次时机让客户揣摩这个数字:
1)假如客户猜的数字比发生的数字值大,则提示“大了”。
2)假如客户猜的数字比发生的数字值小,则提示“小点”
猜对了就过关,猜错Game Over,给玩家重玩的时机。
JSP代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <% String result=(String)request.getAttribute("result"); if(result!=null){ out.write("<font color='red'>"+result+"'</font>"); } %> <% Integer times=(Integer)request.getAttribute("times"); if(times!=null){ out.write("你尚有"+(5-times)+"次时机!"); } %> <br/> <form action="/zxz/zxz" method="POST"> 请输入你的数(20以下):<input type="text" /><br/> <% if(times!=null){ %> <input type="hidden" value="<%=times %>"/> <% } %> <input type="submit" value="竞猜" /> </form> </body> </html>
Servlet代码:
package hah; import java.io.IOException; import java.util.Random; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class zxz */ @WebServlet("/zxz") public class zxz extends HttpServlet { private static final long serialVersionUID = 1L; int answer; public void newGame() { Random random=new Random(); answer=random.nextInt(20); } public zxz() { newGame(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); String lucyStr=request.getParameter("Lucy"); Integer lucyNb=null; System.out.println("谜底:"+answer); if(!lucyStr.equals("")) { lucyNb=Integer.parseInt(lucyStr); } Integer times=1; String timeStr=request.getParameter("times"); if(timeStr!=null&&!timeStr.equals("")) { times=Integer.parseInt(timeStr)+1; } if(times<5) { String result=""; if(lucyNb>answer) { result="大了"; }else if(lucyNb<answer) { result="小了"; }else if(lucyNb==answer) { result="中了"; times=null; } request.setAttribute("times", times); request.setAttribute("result", result); }else { newGame(); response.getWriter().write("游戏竣事<a href='"https://www.jb51.net/+request.getContextPath()+"/One.jsp'>再来一把</a>"); return; } request.getRequestDispatcher("/One.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
总结:
a. 利用标签hidden可以隐式通报数据而不被用户发明 可以用来记录次数 如:
<input type="hidden" value="<%=times %>"/>
b. Servlet是用来跳转和执行逻辑代码的,JSP是用来展示数据的
c. request.getParameter(“Lucy”);假如参数不存在则返回null的字符串值
d 跳转有两种方法 一个是页面跳转 地点要写项目名+jsp可能servlet
另一个是转发共享了request的域工具,地点可以直接写jsp可能servlet 不要项目名 并且项目名和jsp可能servlet前都要加“/” 否则就是相对位置了
如:
<form action="/zxz/zxz" method="POST"> //转发 request.getRequestDispatcher("/One.jsp"). forward(request, response);