第一步:先在Idea里面创建一个web工程
第二步:在src下创建一个servlet类
整个创建好的工程的结构:
第三步:实现
MonkeyGuess类:
package com.gec.playgame;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
public class MonkeyGuess extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//获得打印流
PrintWriter out=response.getWriter();
//获得两个数字,一个在session中的随机数,另外是表单提交的数字
//1、获得session中的数字
HttpSession session=request.getSession(true);
int number=(int)session.getAttribute("number");
//2、获得表单提交的数字
int num=Integer.parseInt(request.getParameter("num"));
//3、判断
if(num==number){
out.println("<font style='color:red'>恭喜您猜中了,兑换一瓶娃哈哈饮料~_~</font>");
Random r=new Random();
int n=r.nextInt(100)+1;
//存入session
session.setAttribute("number",n);
}else if(num>number){
out.println("<font style='color:red'>您猜大了,请重新猜一次~_~</font>");
}else if(num<number){
out.println("<font style='color:red'>您猜小了,请重新猜一次~_~</font>");
}
out.println("<form action='playGames' method='post'>");
out.println("<input type='number' name='num' placeholder=随便猜'>");
out.println("<button type='submit'>猜一猜</button>");
out.println("</form>");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//获得打印流
PrintWriter out=response.getWriter();
//1、画一个表单
out.println("<form action='playGames' method='post'>");
out.println("<input type='number' name='num' placeholder='随便猜'>");
out.println("<button type='submit'>猜一猜</button>");
out.println("</form>");
//2、获得session
HttpSession session=request.getSession(true);
//3、生成一个随机数,存入session
//判断
// if(session.isNew()){如果要加判断可以把index.jsp换成index.html;因为.jsp文件会生成session文件,不会生成新的则判断不了,会造成500服务器错误,而.html不会,html是超文本文件
Random r=new Random();
int n=r.nextInt(100)+1;
//存入session
session.setAttribute("number",n);
System.out.println("number: "+n);
// }
}
}
web.xml里面的配置内容:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>playGames</servlet-name>
<servlet-class>com.gec.playgame.MonkeyGuess</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>playGames</servlet-name>
<url-pattern>/playGames</url-pattern>
</servlet-mapping>
</web-app>
index.jsp里面的内容:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<a href="playGames">欢迎您登录猜数字游戏</a>
</body>
</html>
第四步:部署项目
点击欢迎您登录猜数字游戏: