萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> JSP 程式設計

Servlet Session 完整指南:機制、API、生命週期與最佳實踐

HTTP 無狀態特性使得 Session 成為維持使用者跨請求狀態的核心機制。Servlet 規範定義 javax.servlet.http.HttpSession 介面,容器 (Tomcat/Jetty/Undertow) 實作其儲存、識別 (Cookie/URL Rewriting)、逾時、序列化/集群同步等行為。本文系統梳理 Session 核心 API、工作原理、常見陷阱與生產級最佳實踐。

一、 Session 獲取與建立機制

// 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

底層流程:

  1. 容器檢查 Request Header Cookie: JSESSIONID=xxx 或 URL 參數 ;jsessionid=xxx。
  2. 從 Session 管理器 (Manager) 查找 ID 對應的 Session 物件。
  3. 找到 → 更新最後存取時間、綁定當前請求執行緒上下文 → 返回。
  4. 未找到 + getSession(true) → 生成新 Session ID (安全隨機)、建立 Session 物件、發送 Set-Cookie: JSESSIONID=xxx; Path=/; HttpOnly 給瀏覽器。

二、 核心 API 速查表

方法說明注意事項
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 共享資料入口

三、 Session 識別機制:Cookie vs URL Rewriting

機制原理優點缺點適用場景
Cookie (預設)Set-Cookie: JSESSIONID=xxx; Path=/; HttpOnly; Secure透明、效能佳、支援 HttpOnly 防 XSS、Secure 僅 HTTPS 傳輸用戶可禁用 Cookie99% 現代瀏覽器環境
URL Rewriting所有 URL 附加 ;jsessionid=xxx (路徑參數) 或 ?jsessionid=xxx無需 Cookie 支援URL 醜陋、書籤/分享洩露 Session ID、安全風險高、SEO 不利、需手動編碼所有連結極舊設備/嵌入式瀏覽器禁用 Cookie

啟用 URL Rewriting:response.encodeURL(url) (重導向用 encodeRedirectURL)。容器自動判斷客戶端是否支援 Cookie,不支援時自動附加 Session ID。

四、 Session 儲存與分布式擴充

  1. 記憶體 (預設):Tomcat StandardManager,重啟丟失、單機限制、無法水平擴展。
  2. 檔案持久化:Tomcat PersistentManager + FileStore,重啟恢復、但 I/O 瓶頸、單機。
  3. 資料庫持久化:JDBCStore / DataSourceStore,共享儲存、支援集群、寫入延遲。
  4. Redis / Memcached (推薦生產):Spring Session、Tomcat Redis Session Manager、Jetty Session Cache。高效能、分散式、支援 TTL 自動過期、序列化可插拔 (Jackson/Protostuff/Kryo)。

五、 經典應用場景程式碼

1. 登入驗證與 Session 綁定

@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);
        }
    }
}

2. 登出與 Session 銷毀

@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");
    }
}

3. 購物車 (Session 存放商品 ID 列表,避免大物件)

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);
    }
}

六、 安全強化清單

  1. HttpOnly Cookie:context.xml <Context useHttpOnly="true"> 防止 JS 竊取 JSESSIONID (XSS)。
  2. Secure Cookie:僅 HTTPS 傳輸,<Connector secure="true"> 或負載均衡器終結 SSL 後設定 proxyPort="443" scheme="https" secure="true"。
  3. SameSite 屬性:Tomcat 9.0.31+ / Servlet 5.0 支援 sessionCookieConfig.setSameSite("Lax") (CSRF 防護)。
  4. Session Fixation 防護:登入前後 **更換 Session ID** (Servlet 3.1 request.changeSessionId() 或手動 invalidate() + getSession(true))。
  5. 敏感資料不入 Session**:密碼、信用卡號、身分證號嚴禁存 Session,僅存 ID/Token。
  6. 並發控制:同一用戶並發請求修改 Session 屬性需同步,或改用 Redis 原子操作 (Lua 腳本)。

七、 效能優化建議

  • 縮小 Session 物件:僅存 ID/權限位元組/必要快取 Key,大物件移至 Redis/資料庫。
  • 調整逾時:web.xml <session-timeout>15</session-timeout> (分鐘),平衡安全與體驗。
  • 停用不需要的 Session:純靜態頁面、API 端點、健康檢查端點加 <%@ page session="false" %> 或 Filter 判斷路徑跳過 getSession()。
  • 監控指標:活躍 Session 數、平均大小、序列化耗時、逾時清理頻率 (JMX/Actuator/Prometheus)。

結語

Session 是有狀態 Web 應用的基石,亦是效能與安全的雙刃劍。精通 HttpSession API、理解容器識別與儲存機制、遵循「最小權限、最小存儲、最短壽命」原則,並引入 Redis 等分散式 Session 方案支撐水平擴展,是通往高併發、高可用 Java Web 架構的必經之路。

copyright © 萬盛學電腦網 all rights reserved