| 方法 | 說明 |
|---|---|
| setDomain(String) | 設定適用域名 (如 .example.com) |
| getDomain() | 取得域名 |
| setMaxAge(int) | 設定存活秒數;-1=會話級,0=刪除 |
| getMaxAge() | 取得存活秒數 |
| getName() | 取得 Cookie 名稱 (不可變) |
| setValue(String) | 設定值 |
| getValue() | 取得值 |
| setPath(String) | 設定路徑 (預設當前目錄) |
| getPath() | 取得路徑 |
| setSecure(boolean) | 僅 HTTPS 傳輸 |
| setComment(String) | 用途說明 (瀏覽器可見) |
| getComment() | 取得說明 |
Cookie cookie = new Cookie("RMKEY", useResVo.getRmkey());
cookie.setMaxAge(3600); // 1 小時
cookie.setDomain(".why.com"); // 共享給子域名
cookie.setPath("/"); // 全站有效
response.addCookie(cookie);
多次 new Cookie(...) 並 response.addCookie(),瀏覽器仍只會在同一域名下維護一個文字檔,內含多組鍵值對。
response.addHeader("Set-Cookie",
cookieName + "=" + cookieValue +
";Path=/;Domain=" + domain +
";Max-Age=" + maxAge +
";HttpOnly");
優點:可精確控制 HttpOnly、SameSite 等標準屬性 (Servlet 3.1+ Cookie 類已支援 setHttpOnly()、setAttribute("SameSite", "Strict"))。
// 寫入
Cookie c = new Cookie("name", URLEncoder.encode("中文值", "UTF-8"));
// 讀取
String val = URLDecoder.decode(cookie.getValue(), "UTF-8");
HttpOnly=true 防 XSS 竊取。Secure=true。Max-Age,避免永久 Cookie。