打牌 : da pai ge的个人主页
️个人专栏 : da pai ge的博客专栏
☁️宝剑锋从磨砺出,梅花香自苦寒来
@WebServlet("/html")
public class HtmlServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String name = (String) req.getParameter("name");
resp.setContentType("text/html; charset=utf-8");
resp.getWriter().write(String.format("name: %s
", name));
}
}
@WebServlet("/guessNum")
public class GuessNumServlet extends HttpServlet {
// 要猜的数字
private int toGuess = 0;
// 已经猜了几次
private int count = 0;
private Random random = new Random();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html; charset=utf-8");
// get 方法返回一个初始页面, 并且在服务器中存一个随机数
// 1. 构造随机数, 并清空 count
toGuess = random.nextInt(100) + 1;
System.out.println("toGuess = " + toGuess);
count = 0;
// 2. 返回页面内容
String html = "\n" +
"\n" +
"";
resp.getWriter().write(html);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// post 方法处理猜数字的动作.
resp.setContentType("text/html; charset=utf-8");
// 1. 读取请求中用户猜的数字
int num = Integer.parseInt(req.getParameter("num"));
// 2. 比较大小
String result = "";
if (num < toGuess) {
result = "猜低了";
} else if (num > toGuess) {
result = "猜高了";
} else {
result = "猜对了";
}
count++;
// 3. 构造返回的页面内容
String html = String.format("\n" +
"\n" +
"\n" +
"\n" +
"已经猜了: %d 次\n" +
"结果: %s ", count, result);
resp.getWriter().write(html);
}
}
已经猜了: 次
结果: