项目目录
Login.java
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class Login extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
req.getSession().setAttribute("username",username);
resp.setContentType("text/html;charset=UTF-8");
resp.sendRedirect("/session_last_login_username_war_exploded/index.jsp");
}
}
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="Login" method="post" >
用户名:<input type="text" name="username">
<input type="submit" value="登录">
</form>
</body>
</html>
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>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
</web-app>
效果
发现
server端的session是针对每一个client创建一个session,session对象里的属性:id是区分不同client的关键。
最初client访问server时,server针对每一个client创建一个session,该session对象的属性:id=XXXXX,然后创建cookie,属性name=jsessionid,value=XXXXX,返回给客户端。下次访问server时,以此来判断是哪个client。
在刚才的场景里,client1登录后,server创建该client1的session,属性username = 111。client2登录后,server创建该client2的session,属性username = 444。互不影响。