Session的运行原理:
- 第一次向服务器发送请求时在服务器创建一个Session对象,该对象有一个全球唯一的ID
- 在创建Session对象的同时会创建一个特殊的Cookie对象,该Cookie对象的名字是一个固定值:JSESSIONID,该Cookie对象的值就是Session对象的ID值,并将该Cookie对象发送给浏览器
- 以后浏览器再发送请求就会携带这个特殊的Cookie对象
- 服务器获取Cookie对象的值之后在服务器端寻找与之对象的Session对象一次来区分不同用户
简答实例:
页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>欢迎您,${sessionScope.user }</h1>
</body>
</html>
Servlet:
/**
* 创建或获取Session对象的Servlet
*/
public class CreateOrGetSession extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 创建或获取Session对象
HttpSession session = request.getSession();
//获取Session对象的ID
String id = session.getId();
System.out.println("Session对象的ID值是:"+id);
//向session域中添加一个用户
session.setAttribute("user", "admin");
}