JSP Cookie 处理

在 JSP 里写 Cookie、读 Cookie、删除 Cookie,以及 EL 读取。

Beginner
Key Points写 Cookie 要用 response.addCookie,且必须在任何输出之前;读用 request.getCookies 遍历。

写入

JSP
<%@ page contentType="text/html;charset=UTF-8" %>
<%
    Cookie c = new Cookie("theme", "dark");
    c.setMaxAge(7 * 24 * 3600);
    c.setPath("/");
    c.setHttpOnly(true);
    response.addCookie(c);
%>
<!DOCTYPE html><html><body><p>主题已保存</p></body></html>

addCookie only appends a Set-Cookie line. If the response is already committed (HTML was written), the line is lost — so cookies must be set at the very top of the page.

读取

JSP
<%
    String theme = "light";
    Cookie[] cs = request.getCookies();
    if (cs != null) {
        for (Cookie c : cs) {
            if ("theme".equals(c.getName())) {
                theme = c.getValue();
                break;
            }
        }
    }
%>
<body class="<%= theme %>">

EL 读取

JSP
<p>主题:${cookie.theme.value}</p>
<p>会话:${cookie.JSESSIONID.value}</p>

${cookie.name.value} yields the value, empty when absent. The .value is required — ${cookie.theme} gives the Cookie object itself.

删除

JSP
<%
    Cookie c = new Cookie("theme", "");
    c.setMaxAge(0);
    c.setPath("/");
    response.addCookie(c);
%>
Delete with setMaxAge(0), and the Path must match the original. A different Path is a different cookie and the delete silently fails — the usual cause of "cannot clear the login state".

中文值

JSP
<%
    // 写:Cookie 值不能直接放中文和非 ASCII 字符,要编码
    Cookie c = new Cookie("city",
            java.net.URLEncoder.encode("北京", "UTF-8"));
    c.setMaxAge(3600);
    response.addCookie(c);

    // 读:解码回来
    String city = java.net.URLDecoder.decode(c.getValue(), "UTF-8");
%>

The cookie spec allows only visible ASCII. Raw Chinese is handled inconsistently across containers and browsers, usually truncated or turned into question marks. URLEncoder is the safe route.

Friends & Partners