Cookie cookie = new Cookie("sessionId", "abc123");
cookie.setMaxAge(60 * 30); // 30 分鐘 (秒為單位),負值 = 會話級 (瀏覽器關閉失效)
cookie.setPath("/myapp"); // 生效路徑,默認當前請求路徑
cookie.setDomain(".example.com"); // 可選:跨子域共享
cookie.setHttpOnly(true); // 防 XSS,JS 不可讀取 (Servlet 3.0+)
cookie.setSecure(true); // 僅 HTTPS 傳輸
response.addCookie(cookie);
Cookie[] cookies = request.getCookies(); // 可能返回 null (無 Cookie)
if (cookies != null) {
for (Cookie c : cookies) {
if ("sessionId".equals(c.getName())) {
String value = c.getValue();
// 業務邏輯...
break;
}
}
}
注意:getCookies() 僅返回 當前路徑及其直接父路徑 下的 Cookie,不會遞歸返回所有祖先路徑。
Cookie cookie = new Cookie("sessionId", null); // 值設為 null
cookie.setMaxAge(0); // 立即刪除
cookie.setPath("/myapp"); // **必須與設置時完全一致的路徑**
response.addCookie(cookie);
假設路徑結構:/ → /test → /test/test2 → /test345 → /test555/test666
| 操作 | Firefox 行為 | IE 行為 (歷史參考) |
|---|---|---|
| 設置 | 大小寫敏感,路徑精確匹配 | 鍵名小寫時向上查找父路徑;大寫/混合大小寫僅匹配當前路徑 |
| 刪除 | **必須指定原設置路徑**,大小寫敏感 | 小寫鍵名向上查找父路徑刪除;大寫/混合大小寫不向上查找 |
| 讀取 | 當前路徑 + 直接父路徑 | 同 Firefox |
場景:同一 Tomcat 部署 /app1、/app2 兩個 Context。
app1 設置 Path=/ 的 Cookie,app2 也能讀取/覆蓋 → 業務數據污染。/app1、/app2) 或使用不同域名/子域隔離。// HttpOnly & Secure 標準 API (Tomcat 7+, Jetty 9+)
cookie.setHttpOnly(true);
cookie.setSecure(true);
// SameSite 屬性 (Servlet API 無標準方法,需手動添加 Header)
response.addHeader("Set-Cookie", "sessionId=abc123; Path=/myapp; HttpOnly; Secure; SameSite=Strict");
public final class CookieUtils {
public static void add(HttpServletResponse resp, String name, String value, int maxAgeSec, String path) {
Cookie c = new Cookie(name, value);
c.setMaxAge(maxAgeSec);
c.setPath(path != null ? path : "/");
c.setHttpOnly(true);
resp.addCookie(c);
}
public static String get(HttpServletRequest req, String name) {
Cookie[] cs = req.getCookies();
if (cs == null) return null;
for (Cookie c : cs) if (name.equals(c.getName())) return c.getValue();
return null;
}
public static void remove(HttpServletResponse resp, String name, String path) {
Cookie c = new Cookie(name, null);
c.setMaxAge(0);
c.setPath(path != null ? path : "/");
resp.addCookie(c);
}
}