Servlet Cookie 处理
Cookie 的读写删、生命周期、Path 与 Domain、HttpOnly 与 Secure。
Key PointsCookie 存在客户端,每次请求自动带上;删 Cookie 靠 setMaxAge(0),不是真的删除文件。
写 Cookie
Java
Cookie c = new Cookie("theme", "dark");
c.setMaxAge(7 * 24 * 3600); // 秒;负数=会话级,0=立即删除
c.setPath("/"); // 全站可见,默认是当前 Servlet 的路径
c.setHttpOnly(true); // 禁止 JS 读取,防 XSS 窃取
c.setSecure(true); // 只在 HTTPS 下发送
resp.addCookie(c);Output
Set-Cookie: theme=dark; Max-Age=604800; Path=/; HttpOnly; Secure读 Cookie
Java
private static String cookie(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;
}getCookies() may return null when the browser sends none, so null-check first. Looking one up by name needs a manual loop — there is no getCookie(name).
删 Cookie
Java
Cookie c = new Cookie("theme", "");
c.setMaxAge(0);
c.setPath("/"); // 必须与原 Cookie 的 Path 一致,否则删不掉
resp.addCookie(c);Deleting a cookie only marks it expired. If
Path or Domain differ from the original, the browser treats them as separate cookies and the delete silently fails — a common cause of "still logged in after logout".四个属性
| Attribute | Effect |
|---|---|
| Max-Age | 正数=秒;负数=关浏览器即失效;0=删除 |
| Path | 只有该路径下的请求才带此 Cookie |
| Domain | 子域名共享;不设则仅当前域名 |
| HttpOnly / Secure | 禁 JS 读取 / 只走 HTTPS |
Cookies cap at about 4KB each with a per-domain count limit, and they sit in plain text on the user's machine. Store an identifier, not data — keep real state in the server-side session and only the id in the cookie.
写 Cookie
Java
Cookie c = new Cookie("theme", "dark");
c.setMaxAge(7 * 24 * 3600); // 秒;负数=会话级,0=立即删除
c.setPath("/"); // 全站可见,默认是当前 Servlet 的路径
c.setHttpOnly(true); // 禁止 JS 读取,防 XSS 窃取
c.setSecure(true); // 只在 HTTPS 下发送
resp.addCookie(c);Output
Set-Cookie: theme=dark; Max-Age=604800; Path=/; HttpOnly; Secure读 Cookie
Java
private static String cookie(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;
}getCookies() 可能返回 null(浏览器一个 Cookie 都没带),必须先判空。按名字取需要自己遍历——API 没有 getCookie(name)。
删 Cookie
Java
Cookie c = new Cookie("theme", "");
c.setMaxAge(0);
c.setPath("/"); // 必须与原 Cookie 的 Path 一致,否则删不掉
resp.addCookie(c);删 Cookie 只是让浏览器把它标记为过期。如果
Path 或 Domain 与原 Cookie 不一致,浏览器会认为是两个不同的 Cookie,删除无效——这是「登出后还是登录状态」的常见原因。四个属性
| 属性 | 作用 |
|---|---|
| 存活时间 | 正数=秒;负数=关浏览器即失效;0=删除 |
| 作用路径 | 只有该路径下的请求才带此 Cookie |
| 作用域 | 子域名共享;不设则仅当前域名 |
| 安全 | 禁 JS 读取 / 只走 HTTPS |
Cookie 有 4KB 大小上限、每个域名数量也有上限,而且明文存在用户机器上。只放标识,不放数据——真正的状态放服务端 Session,Cookie 里只存那个 ID。