编写servlet,产生一个1-10的随机数,将其保存到session中,然后重定向到输入页面input.jsp,在此页面输入所猜测的数后,提交到另一个servlet判断是否正确,若不正确,转发到input.jsp,在此页面显示“大了”或“小了”的提示信息,若正确,则在新页面显示“答对了”。(网页版的猜数游戏)
时间: 2023-06-23 20:10:31 浏览: 72
首先,我们需要编写一个随机数生成的servlet,代码如下:
```java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RandomNumberServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
// 生成随机数并将其保存到session中
int randomNumber = (int) (Math.random() * 10 + 1);
session.setAttribute("randomNumber", randomNumber);
// 重定向到输入页面
response.sendRedirect("input.jsp");
}
}
```
接下来是输入页面input.jsp的代码:
```html
<!doctype html>
<html>
<head>
<title>猜数游戏</title>
</head>
<body>
<form action="GuessNumberServlet" method="post">
<label>请输入1-10之间的整数:</label>
<input type="text" name="guessNumber" />
<br />
<input type="submit" value="提交" />
</form>
</body>
</html>
```
然后是判断猜测的数是否正确的servlet:
```java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GuessNumberServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
// 获取随机数和用户猜测的数
int randomNumber = (int) session.getAttribute("randomNumber");
int guessNumber = Integer.parseInt(request.getParameter("guessNumber"));
// 判断是否猜对
if (randomNumber == guessNumber) {
// 猜对,跳转到结果页面
response.sendRedirect("success.jsp");
} else {
// 猜错,转发到输入页面并显示提示信息
String message = guessNumber > randomNumber ? "大了" : "小了";
request.setAttribute("message", message);
RequestDispatcher dispatcher = request.getRequestDispatcher("input.jsp");
dispatcher.forward(request, response);
}
}
}
```
最后是结果页面success.jsp,代码如下:
```html
<!doctype html>
<html>
<head>
<title>猜数游戏</title>
</head>
<body>
<h1>恭喜你,猜对了!</h1>
</body>
</html>
```
完成以上代码后,我们需要在web.xml文件中配置servlet和jsp的映射关系,代码如下:
```xml
<web-app>
<servlet>
<servlet-name>RandomNumberServlet</servlet-name>
<servlet-class>RandomNumberServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>GuessNumberServlet</servlet-name>
<servlet-class>GuessNumberServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RandomNumberServlet</servlet-name>
<url-pattern>/random</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>GuessNumberServlet</servlet-name>
<url-pattern>/guess</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>random</welcome-file>
</welcome-file-list>
</web-app>
```
其中,RandomNumberServlet映射到/random,GuessNumberServlet映射到/guess,welcome-file为random,表示访问web应用时默认跳转到RandomNumberServlet。
阅读全文