(1)编写getNumber.jsp, 生成1-100之间随机数 将该数存入session 给出超链接去玩猜数游戏,效果如下图 (2)编写inputNumber.jsp,输入用户猜测数字,显示猜测结论提示信息 (3)编写ServletHandleGuess.java
时间: 2024-03-25 13:39:30 浏览: 84
getNumber.jsp代码如下:
```jsp
<%
int randomNum = (int)(Math.random()*100) + 1; // 生成1~100之间的随机数
session.setAttribute("randomNum", randomNum); // 将随机数存入session中
%>
<html>
<head>
<title>猜数字游戏</title>
</head>
<body>
<h1>猜数字游戏</h1>
<p>随机数已生成,现在开始游戏吧!</p>
<a href="inputNumber.jsp">开始游戏</a>
</body>
</html>
```
inputNumber.jsp代码如下:
```jsp
<%
int randomNum = (int)session.getAttribute("randomNum"); // 从session中取出随机数
String msg = "";
if(request.getMethod().equals("POST")) { // 如果是POST请求
int guessNum = Integer.parseInt(request.getParameter("guessNum")); // 获取用户猜的数字
if(guessNum == randomNum) {
msg = "恭喜你,猜对了!";
} else if(guessNum < randomNum) {
msg = "猜小了,请再试一次!";
} else {
msg = "猜大了,请再试一次!";
}
}
%>
<html>
<head>
<title>猜数字游戏</title>
</head>
<body>
<h1>猜数字游戏</h1>
<p>已生成1~100之间的随机数,请猜测这个数字:</p>
<form method="post">
<input type="text" name="guessNum">
<input type="submit" value="提交">
</form>
<p><%=msg%></p>
</body>
</html>
```
ServletHandleGuess.java代码如下:
```java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/ServletHandleGuess")
public class ServletHandleGuess extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
int randomNum = (int)session.getAttribute("randomNum"); // 从session中取出随机数
int guessNum = Integer.parseInt(request.getParameter("guessNum")); // 获取用户猜的数字
String msg = "";
if(guessNum == randomNum) {
msg = "恭喜你,猜对了!";
} else if(guessNum < randomNum) {
msg = "猜小了,请再试一次!";
} else {
msg = "猜大了,请再试一次!";
}
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>猜数字游戏</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>猜数字游戏</h1>");
out.println("<p>已生成1~100之间的随机数,请猜测这个数字:</p>");
out.println("<form method=\"post\">");
out.println("<input type=\"text\" name=\"guessNum\">");
out.println("<input type=\"submit\" value=\"提交\">");
out.println("</form>");
out.println("<p>" + msg + "</p>");
out.println("</body>");
out.println("</html>");
}
}
```
阅读全文