1. Design the login interface (index)
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false"%>
<html>
<head>
<title>登录</title>
</head>
<body>
<h1>登录</h1>
<div style="text-align: center">
<%--这里表单表示的意思:以post方式提交表单,提交到login请求--%>
<form action="${pageContext.request.contextPath}/login" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
爱好:
<input type="checkbox" value="游戏" name="hobbys" >游戏
<input type="checkbox" value="敲代码" name="hobbys" >敲代码
<input type="checkbox" value="唱歌" name="hobbys" >唱歌
<input type="checkbox" value="看电影" name="hobbys" >看电影
<br>
<input type="submit">
</form>
</div>
</body>
</html>
2. Design the success page
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>成功</title>
</head>
<body>
<h1>登陆成功</h1>
</body>
</html>
3. Create a LoginServlet class to obtain front-end information and use request forwarding to jump to the success page
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password=req.getParameter("password");
String[] hobbys = req.getParameterValues("hobbys");
System.out.println("==============================");
System.out.println(username);
System.out.println(password);
System.out.println(Arrays.toString(hobbys));
System.out.println("==============================");
//通过请求转发 请求转发不需要带项目名字,直接相对URL 重定向才需要/r
resp.setCharacterEncoding("utf-8");
//这里的/代表当前的web应用
req.getRequestDispatcher("/success.jsp").forward(req,resp);//可以是相对路径也可以是绝对路径
//this.getServletContext().getRequestDispatcher(url);这里的Url只能是绝对路径
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
Four, register servlet
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.huang.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
5. Configure Tomcat and run it
After the request jumps, it is still on the /login page, but the content becomes the page in success.jsp