HTTP 無狀態特性使得 Session 成為維持使用者跨請求狀態的核心機制。Servlet 規範定義 javax.servlet.http.HttpSession 介面,容器 (Tomcat/Jetty/Undertow) 實作其儲存、識別 (Cookie/URL Rewriting)、逾時、序列化/集群同步等行為。本文系統梳理 Session 核心 API、工作原理、常見陷阱與生產級最佳實踐。
// 1. 獲取或建立 (最常用)
HttpSession session = request.getSession(); // 等同 getSession(true)
HttpSession session = request.getSession(true); // 存在回傳,不存在建立新 Session
// 2. 僅獲取,不建立
HttpSession session = request.getSession(false); // 存在回傳,不存在回傳 null
// 3. 判斷是否為新建立
boolean isNew = session.isNew(); // 新建立返回 true,客戶端已有 Session ID 返回 false
底層流程:
Cookie: JSESSIONID=xxx 或 URL 參數 ;jsessionid=xxx。getSession(true) → 生成新 Session ID (安全隨機)、建立 Session 物件、發送 Set-Cookie: JSESSIONID=xxx; Path=/; HttpOnly 給瀏覽器。| 方法 | 說明 | 注意事項 |
|---|---|---|
setAttribute(String name, Object value) | 綁定屬性 (覆蓋同名) | value 必須可序列化 (實作 Serializable) 以支援分布式/持久化 |
getAttribute(String name) | 取得屬性,不存在回傳 null | 需檢查 null 再轉型 |
removeAttribute(String name) | 移除屬性 | 不存在不拋異常 |
getAttributeNames() | 返回所有屬性名 Enumeration | 遍歷時不可修改 Session 屬性 |
invalidate() | 使 Session 無效,移除所有屬性 | 後續操作拋 IllegalStateException;登出必呼叫 |
isNew() | 是否為當前請求新建立 | 僅在建立該請求的 Session 時為 true |
getId() | 取得 Session ID (JSESSIONID) | 不可變,唯一標識 |
getCreationTime() | 建立時間 (毫秒時間戳) | long |
getLastAccessedTime() | 最後存取時間 | 容器定期掃描此值清理逾期 Session |
getMaxInactiveInterval() / setMaxInactiveInterval(int seconds) | 獲取/設定逾時秒數 (負數 = 永不逾時) | 優先於 web.xml 設定;0 或負數慎用 |
getServletContext() | 取得 ServletContext (應用程式級共享) | 跨 Session 共享資料入口 |
| 機制 | 原理 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|---|
| Cookie (預設) | Set-Cookie: JSESSIONID=xxx; Path=/; HttpOnly; Secure | 透明、效能佳、支援 HttpOnly 防 XSS、Secure 僅 HTTPS 傳輸 | 用戶可禁用 Cookie | 99% 現代瀏覽器環境 |
| URL Rewriting | 所有 URL 附加 ;jsessionid=xxx (路徑參數) 或 ?jsessionid=xxx | 無需 Cookie 支援 | URL 醜陋、書籤/分享洩露 Session ID、安全風險高、SEO 不利、需手動編碼所有連結 | 極舊設備/嵌入式瀏覽器禁用 Cookie |
啟用 URL Rewriting:response.encodeURL(url) (重導向用 encodeRedirectURL)。容器自動判斷客戶端是否支援 Cookie,不支援時自動附加 Session ID。
StandardManager,重啟丟失、單機限制、無法水平擴展。PersistentManager + FileStore,重啟恢復、但 I/O 瓶頸、單機。JDBCStore / DataSourceStore,共享儲存、支援集群、寫入延遲。Spring Session、Tomcat Redis Session Manager、Jetty Session Cache。高效能、分散式、支援 TTL 自動過期、序列化可插拔 (Jackson/Protostuff/Kryo)。@WebServlet("/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
User user = userService.authenticate(username, password);
if (user != null) {
HttpSession session = req.getSession(true); // 建立/取得 Session
session.setAttribute("LOGIN_USER", user); // 存入用戶實體 (需 Serializable)
session.setMaxInactiveInterval(30 * 60); // 30 分鐘逾時
// 防 Session Fixation 攻擊:登入成功後換發新 Session ID
// 容器自動處理:request.changeSessionId() (Servlet 3.1+)
resp.sendRedirect(req.getContextPath() + "/dashboard");
} else {
req.setAttribute("error", "帳號或密碼錯誤");
req.getRequestDispatcher("/login.jsp").forward(req, resp);
}
}
}
@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
HttpSession session = req.getSession(false);
if (session != null) {
session.invalidate(); // 徹底銷毀
}
resp.sendRedirect(req.getContextPath() + "/login.jsp");
}
}
public class CartService {
private static final String CART_KEY = "SHOPPING_CART";
public List getCart(HttpSession session) {
return (List) session.getAttribute(CART_KEY);
}
public void addItem(HttpSession session, Long productId) {
List cart = getCart(session);
if (cart == null) {
cart = new ArrayList<>();
session.setAttribute(CART_KEY, cart);
}
cart.add(productId);
}
}
context.xml <Context useHttpOnly="true"> 防止 JS 竊取 JSESSIONID (XSS)。<Connector secure="true"> 或負載均衡器終結 SSL 後設定 proxyPort="443" scheme="https" secure="true"。sessionCookieConfig.setSameSite("Lax") (CSRF 防護)。request.changeSessionId() 或手動 invalidate() + getSession(true))。web.xml <session-timeout>15</session-timeout> (分鐘),平衡安全與體驗。<%@ page session="false" %> 或 Filter 判斷路徑跳過 getSession()。Session 是有狀態 Web 應用的基石,亦是效能與安全的雙刃劍。精通 HttpSession API、理解容器識別與儲存機制、遵循「最小權限、最小存儲、最短壽命」原則,並引入 Redis 等分散式 Session 方案支撐水平擴展,是通往高併發、高可用 Java Web 架構的必經之路。