import java.io.IOException;
@WebServlet(name = "loginServlet", value = "/loginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if ("username".equals(username) && "password".equals(password)) {
request.setAttribute("username", username);
request.setAttribute("password", password);
request.getRequestDispatcher("userinfo.jsp").forward(request, response);
} else {
response.sendRedirect("index.jsp");
}
}
}
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>JSP - Hello World</title>
</head>
<body>
<h2>用户登录</h2>
<form action="loginServlet" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
![](https://i-blog.csdnimg.cn/blog_migrate/ed8f7d85c4df1dc6e826f9cdfacaeea2.png)
![](https://i-blog.csdnimg.cn/blog_migrate/f4caa0c103b31fc6e105d3b3825a1928.png)