Cookie 是伺服器發送至瀏覽器的小型文字資料,瀏覽器儲存後後續請求自動攜帶,實現 HTTP 無狀態協議下的狀態保持(如登入態、偏好設定、追蹤 ID)。
<%@ page contentType="text/html; charset=UTF-8" %>
<%
// 1. 建立 Cookie(名稱、值)
Cookie cookie = new Cookie("username", "JohnDoe");
// 2. 設定屬性
cookie.setMaxAge(60 * 60 * 24 * 30); // 存活 30 天(秒),負數=會話級,0=刪除
cookie.setPath("/"); // 生效路徑,預設為當前路徑
cookie.setDomain(".example.com"); // 跨子域共享(可選)
cookie.setSecure(true); // 僅 HTTPS 傳輸(可選)
cookie.setHttpOnly(true); // 防止 JS 存取,防 XSS(Servlet 3.0+)
// 3. 寫入回應
response.addCookie(cookie);
%>
<html><body>Cookie 已寫入</body></html>
<%
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie c : cookies) {
String name = c.getName();
String value = c.getValue();
out.println("Name: " + name + ", Value: " + value + "<br>");
// 依名稱取值
if ("username".equals(name)) {
// 取得目標 Cookie
}
}
}
%>
| 屬性 | 方法 | 說明 |
|---|---|---|
| 名稱 | 建構子 | 不可變,建立時指定 |
| 值 | getValue/setValue | 儲存資料,建議 URL 編碼 |
| MaxAge | setMaxAge(int 秒) | >0 持久化;=0 刪除;<0 會話級(關閉瀏覽器失效) |
| Path | setPath(String) | URL 路徑前綴匹配,預設為建立 Cookie 的路徑 |
| Domain | setDomain(String) | 跨子域共享,如 .example.com 覆蓋 a.example.com |
| Secure | setSecure(boolean) | 僅 HTTPS 傳輸 |
| HttpOnly | setHttpOnly(boolean) | 禁止 JavaScript 存取,降低 XSS 風險 |
javax.servlet.http.Cookie 只支援此版本。URLEncoder.encode(value, "UTF-8"),讀取後 URLDecoder.decode。public final class CookieUtils {
public static void addCookie(HttpServletResponse resp, String name, String value,
int maxAge, String path, String domain, boolean secure, boolean httpOnly) {
Cookie c = new Cookie(name, value);
c.setMaxAge(maxAge);
if (path != null) c.setPath(path);
if (domain != null) c.setDomain(domain);
c.setSecure(secure);
c.setHttpOnly(httpOnly);
resp.addCookie(c);
}
public static String getCookie(HttpServletRequest req, String name) {
Cookie[] cs = req.getCookies();
if (cs != null) for (Cookie c : cs) if (name.equals(c.getName())) return c.getValue();
return null;
}
public static void removeCookie(HttpServletResponse resp, String name, String path, String domain) {
addCookie(resp, name, "", 0, path, domain, false, false);
}
}
Secure=true; HttpOnly=true。Path=/; HttpOnly=true。