JSP Cookie 处理
在 JSP 里写 Cookie、读 Cookie、删除 Cookie,以及 EL 读取。
写入
<%@ 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.
读取
<%
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 读取
<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.
删除
<%
Cookie c = new Cookie("theme", "");
c.setMaxAge(0);
c.setPath("/");
response.addCookie(c);
%>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".中文值
<%
// 写: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.
写入
<%@ 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 只是往响应头里加一行 Set-Cookie。如果它执行时响应已经提交(前面有 HTML 输出了),这行头就丢了——所以 Cookie 必须写在页面最前面。
读取
<%
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 读取
<p>主题:${cookie.theme.value}</p>
<p>会话:${cookie.JSESSIONID.value}</p>EL 里 ${cookie.名字.value} 直接取到值,取不到时是空串。注意 .value 不能省——${cookie.theme} 得到的是 Cookie 对象本身。
删除
<%
Cookie c = new Cookie("theme", "");
c.setMaxAge(0);
c.setPath("/");
response.addCookie(c);
%>setMaxAge(0),并且 Path 必须与原 Cookie 一致。Path 不同浏览器视为两个 Cookie,删除无效——「清不掉登录状态」基本都是这个原因。中文值
<%
// 写: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");
%>Cookie 规范只允许 ASCII 可见字符。直接塞中文,不同容器和浏览器的处理不一致,常见结果是值被截断或变成问号。用 URLEncoder 编码是最稳的做法。