设计一个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" name="Lucy" /><br/>
<%
if(times!=null){
%>
<input type="hidden" name="times" 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='"+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);
}
}
总结:
- 使用标签hidden可以隐式传递数据而不被用户发现 可以用来记录次数 如:
<input type="hidden" name="times" value="<%=times %>"/>
Servlet是用来跳转和执行逻辑代码的,JSP是用来展示数据的
- request.getParameter("Lucy");如果参数不存在则返回null的字符串值
- 跳转有两种方式 一个是页面跳转 地址要写项目名+jsp或者servlet
另一个是转发共享了request的域对象,地址可以直接写jsp或者servlet 不要项目名 而且项目名和jsp或者servlet前都要加“/”
不然就是相对位置了
如:
<form action="/zxz/zxz" method="POST">
//转发
request.getRequestDispatcher("/One.jsp").
forward(request, response);