核心概念
要明白几个关键点:

- Session 是什么? Session 是服务器为了保存特定用户的状态信息而创建的一个对象,当用户第一次访问网站时,服务器会为其创建一个唯一的 Session ID,并将其发送给浏览器(通常通过 Cookie),之后,浏览器每次请求都会带上这个 Session ID,服务器通过 ID 找到对应的 Session 对象。
- 获取的是什么? 我们通常说的“获取 Session ID”,指的是获取服务器为当前会话分配的那个唯一字符串标识符。
在 Java Web 应用中(Servlet/JSP)
这是最传统和基础的 Java Web 开发方式,在 Servlet 中,你可以通过 HttpServletRequest 对象来获取 Session。
获取 Session 对象,然后从对象中获取 ID
这是最标准的方法。
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
// 在你的 Servlet 或 Filter 的 service/doFilter 方法中
// HttpServletRequest request 是参数
// 1. 获取当前请求的 Session 对象
// 如果当前请求没有关联的 Session,且 createIfAbsent 为 true(默认值),则会创建一个新的 Session。
// 如果设置为 false,则当没有 Session 时会返回 null。
HttpSession session = request.getSession();
// 2. 从 Session 对象中获取 ID
String sessionId = session.getId();
// 打印出来看看
System.out.println("当前 Session ID 是: " + sessionId);
// 将 ID 存入请求作用域,以便在 JSP 中使用
request.setAttribute("currentSessionId", sessionId);
// 转发到 JSP 页面
request.getRequestDispatcher("/showSessionId.jsp").forward(request, response);
request.getSession() vs request.getSession(false)
request.getSession()或request.getSession(true):如果用户没有 Session,服务器会自动创建一个新的 Session,这是最常用的方式,适用于需要为用户建立会话的场景(例如用户登录后)。request.getSession(false):如果用户没有 Session,这个方法会返回null,而不会创建新的 Session,这适用于只想检查用户是否已有会话,而不想强制创建的场景。
在 JSP 中直接获取
在 JSP 页面中,你可以使用内置的 session 对象(它是一个 HttpSession 实例)来直接获取 ID。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>显示 Session ID</title>
</head>
<body>
<h1>Session ID 信息</h1>
<p>当前 Session ID 是: <strong>${pageContext.session.id}</strong></p>
<!-- 或者使用 scriptlet 语法 (不推荐,但可以工作) -->
<%-- <p>当前 Session ID 是: <strong><%= session.getId() %></strong></p> --%>
<p>Session 创建时间: <%= new Date(session.getCreationTime()) %></p>
<p>Session 最后访问时间: <%= new Date(session.getLastAccessedTime()) %></p>
</body>
</html>
${pageContext.session.id}是 JSTL/EL 表达式的写法,更简洁。<%= session.getId() %>是传统的 JSP scriptlet 写法,功能相同。
在 Spring Boot 应用中
Spring Boot 对 Servlet API 进行了封装,使得获取 Session 更加方便。
在 Controller 中获取(最常见)
Spring 的 HttpSession 对象就是 Servlet API 中的 HttpSession,你可以直接将其作为 Controller 方法的参数注入。
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/session")
public class SessionController {
@GetMapping("/show")
public String showSessionId(HttpSession session, Model model) {
// Spring 自动将 session 对象注入,这里直接使用
String sessionId = session.getId();
System.out.println("Spring Boot 中获取的 Session ID: " + sessionId);
// 将数据放入 Model,用于在 Thymeleaf 或其他模板引擎中显示
model.addAttribute("sessionId", sessionId);
// 返回视图名称
return "session-info"; // 对应 src/main/resources/templates/session-info.html
}
}
对应的 Thymeleaf 模板 (session-info.html)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>Session Info</title>
</head>
<body>
<h1>Spring Boot Session ID</h1>
<p>当前 Session ID 是: <span th:text="${sessionId}"></span></p>
</body>
</html>
在非 Web 环境中(如独立应用程序)
如果你的 Java 程序不是一个 Web 应用(例如一个桌面应用或后台服务),那么没有 Session 的概念,Session 是一个由 Web 容器(如 Tomcat, Jetty)管理的、与 HTTP 协议紧密相关的机制。

在这种情况下,如果你需要实现一个类似“会话”的功能来管理用户状态,你有以下几种选择:
-
使用内存缓存:可以使用
ConcurrentHashMap来存储会话数据,用 UUID 作为 Key。import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; public class InMemorySessionManager { // 使用线程安全的 ConcurrentHashMap 存储会话 private static final ConcurrentHashMap<String, Object> sessionStore = new ConcurrentHashMap<>(); public String createSession() { String sessionId = UUID.randomUUID().toString(); sessionStore.put(sessionId, new Object()); // 存储一个简单的对象或用户数据 return sessionId; } public Object getSessionData(String sessionId) { return sessionStore.get(sessionId); } } -
使用专业的会话框架:如 Apache Shiro,它提供了一个强大且易用的会话管理框架,不仅适用于 Web 环境,也适用于任何 Java SE 应用。
总结与对比
| 场景 | 核心对象 | 关键代码 | 说明 |
|---|---|---|---|
| Servlet/JSP | HttpServletRequest, HttpSession |
HttpSession session = request.getSession();String id = session.getId(); |
最基础的方式,所有 Java Web 容器都支持。 |
| Spring Boot | HttpSession (注入) |
public String myMethod(HttpSession session) |
Spring MVC 对 Servlet API 的友好封装,直接在方法参数中声明即可。 |
| 非 Web 环境 | 无(需自行实现) | String id = UUID.randomUUID().toString(); |
Web Session 不存在,需使用其他技术(如内存、Redis、Shiro)实现会话逻辑。 |
最佳实践建议:
- 在 Web 应用中:始终使用
request.getSession()来获取会话,这是最标准、最可靠的方式。 - 在 Spring 应用中:优先使用 Controller 方法参数注入
HttpSession,代码更简洁,符合 Spring 的设计哲学。 - 不要手动解析 Cookie:虽然 Session ID 通常存在名为
JSESSIONID的 Cookie 中,但你不应该自己去解析 Cookie,因为 Session 的管理机制可能由容器配置(URL 重写),直接通过request.getSession()获取是封装了所有底层细节的正确做法。
