Servlet Cookie 处理

Cookie 的读写删、生命周期、Path 与 Domain、HttpOnly 与 Secure。

Beginner
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".

四个属性

AttributeEffect
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.

Friends & Partners