萬盛學電腦網

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

Java Cookie 操作完整指南:建立、讀取、刪除、路徑匹配規則與跨應用陷阱

Cookie 基礎 API

// 建立
Cookie cookie = new Cookie("name", "value");
cookie.setMaxAge(60);           // 秒;負數=會話級(關閉瀏覽器失效);0=立即刪除
cookie.setPath("/app");         // 生效路徑,預設為當前請求路徑
cookie.setDomain(".example.com"); // 跨子域共享 (可選)
cookie.setSecure(true);         // 僅 HTTPS 傳輸 (可選)
cookie.setHttpOnly(true);       // 防 XSS,JS 無法讀取 (Servlet 3.0+)
response.addCookie(cookie);

// 讀取
Cookie[] cookies = request.getCookies(); // 可能為 null
if (cookies != null) {
    for (Cookie c : cookies) {
        if ("name".equals(c.getName())) {
            String value = c.getValue();
            break;
        }
    }
}

// 刪除 (必須同名、同路徑、同域)
Cookie del = new Cookie("name", null);
del.setMaxAge(0);
del.setPath("/app"); // 必須與建立時一致
response.addCookie(del);

路徑匹配規則深度解析

Cookie 的 `Path` 屬性決定**哪些請求會攜帶此 Cookie**。

  • 瀏覽器發送請求時,**請求路徑必須以 Cookie Path 為前綴**才會附上 Cookie。
  • Path **區分大小寫** (RFC 6265),Tomcat 預設嚴格遵守。
  • 預設 Path = 請求 URI 的**目錄部分** (不含檔名)。例:請求 `/app/user/profile.jsp` → 預設 Path `/app/user/`。

實戰陷阱

建立時 Path請求路徑是否攜帶說明
/app/app/user/list✅前綴匹配
/app/user/app/admin❌非前綴
/app//app❌/app 不是 /app/ 的前綴 (缺尾斜線)
建議:統一使用**絕對路徑且以 `/` 結尾** (如 `/app/`) 或根路徑 `/`,避免尾斜線陷阱。

刪除 Cookie 的瀏覽器差異 (歷史遺留)

  • Firefox/Chrome (現代):必須**完全匹配**建立時的 `name` (大小寫敏感)、`path`、`domain` 才能刪除。
  • IE6-11 (歷史):
    • 名稱小寫:向上查找父路徑刪除 (如 `/app/user` → `/app` → `/`)。
    • 名稱含大寫:**不向上查找**,僅刪除當前路徑。

**結論**:刪除時**必須精確複製**建立時的 `name`、`path`、`domain`,不可偷懶。

多 WebApp 共享主機的隔離問題

Tomcat 以 `ContextPath` 隔離應用 (如 `/app1`、`/app2`)。

  • 若 Cookie `Path=/`,**所有應用互相可見**,極易衝突 (同名覆蓋、誤刪)。
  • 鐵律:每個 WebApp **只在自己的 ContextPath 下操作 Cookie** (`cookie.setPath(request.getContextPath() + "/")`)。
  • 跨應用共享 Session/SSO 請用 **Redis + Token** 或 **CAS/OAuth2**,勿靠 Cookie Path=/ 硬共享。

完整實戰範例:登入記住帳號

<%-- login.jsp --%>
<form action="login.do" method="post">
    帳號: <input name="username" value="<%=getCookieValue(request, "remember_user")%>" />
    密碼: <input type="password" name="password" />
    <label><input type="checkbox" name="remember" value="1"> 記住我</label>
    <button>登入</button>
</form>

<%!
    // 讀取 Cookie 工具
    public static String getCookieValue(HttpServletRequest req, String name) {
        Cookie[] cs = req.getCookies();
        if (cs != null) for (Cookie c : cs) if (name.equals(c.getName())) return c.getValue();
        return "";
    }
%>
// LoginServlet.doPost
String user = request.getParameter("username");
String pass = request.getParameter("password");
boolean remember = "1".equals(request.getParameter("remember"));

if (authService.login(user, pass)) {
    HttpSession session = request.getSession();
    session.setAttribute("user", user);

    if (remember) {
        Cookie c = new Cookie("remember_user", user);
        c.setMaxAge(30 * 24 * 3600); // 30 天
        c.setPath(request.getContextPath() + "/"); // 關鍵:限定在本應用
        c.setHttpOnly(true);
        response.addCookie(c);
    } else {
        // 取消記住:刪除 Cookie
        Cookie c = new Cookie("remember_user", null);
        c.setMaxAge(0);
        c.setPath(request.getContextPath() + "/");
        response.addCookie(c);
    }
    response.sendRedirect("index.jsp");
} else {
    request.setAttribute("error", "帳號密碼錯誤");
    request.getRequestDispatcher("login.jsp").forward(request, response);
}
copyright © 萬盛學電腦網 all rights reserved