1.新建web application項目,設(shè)置好服務(wù)器和library。
2.添加login.jsp, success.jsp, fail.jsp三個文件:
- login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>login</title>
</head>
<body>
<form action="<%= request.getContextPath()%>/servlet/LoginServlet" method="post">
username:<input type="text" name="username">
password:<input type="password" name="password">
<input type="submit" value="submit">
</form>
</body>
</html>
- success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
login successfully! welcome ${username}
</body>
</html>
- fail.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
login fail
</body>
</html>
3.新建servlet包--LoginServlet類
- LoginServlet
package servlet;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class LoginServlet extends javax.servlet.http.HttpServlet {
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if ("admin".equals(username) && "admin".equals(password)) {
//check success
HttpSession session = request.getSession();
session.setAttribute("username", username);
response.sendRedirect(request.getContextPath() + "/success.jsp");
} else {
//check fail
response.sendRedirect(request.getContextPath() + "/fail.jsp");
}
}
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
}
}
4.修改web.xml
- 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_3_1.xsd" version="3.1">
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/servlet/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>
5.啟動服務(wù)器打開127.0.0.1:8080/project_name/login.jsp
6.弊端:
不安全,可以隨意打開success.jsp