Xer*_*oid 1 java cookies session servlets
我遇到了在Servlet中正确设置(持久/跨浏览器会话)cookie的数据以及在Filter中读取它的问题.
Servlet的代码(在登录时运行)是:
String encodedValue = new String(Base64
.encodeBase64(req.getParameter("account").getBytes()));
Cookie cookie = new Cookie("projectAuthenticationCookie", encodedValue );
cookie.setMaxAge(24*60*60);
cookie.setPath("/");
res.addCookie(cookie);
Run Code Online (Sandbox Code Playgroud)
这将在响应中获取cookie,但是当我在我的过滤器中使用以下代码读取它时:
Cookie authenticationCookie = null;
Cookie[] cookies = ((HttpServletRequest) request).getCookies();
for (Cookie cookie : cookies){
if ("projectAuthenticationCookie".equals(cookie.getName())) {
authenticationCookie = cookie;
}
}
Run Code Online (Sandbox Code Playgroud)
我只得到我设置的值,所有其他字段都是null,空或不同.例如,最大年龄总是返回-1,因此cookie永远不会持久.

我尝试使用以下命令设置expires-header:
res.setDateHeader("Expires", System.currentTimeMillis() + 24*60*60*1000);
Run Code Online (Sandbox Code Playgroud)
当我读到没有有效的expires-header时,会话将会超时(如果我错了,请纠正我),但这也无济于事......
我想到的一个问题是我在localhost上运行(尝试设置cookie.setDomain("localhost")但也没有运气).我的web服务器/ serclet容器是Jetty 7,但我不认为这是相关的......
任何提示?
对于从请求中获取的cookie,不会填充名称和值以外的字段(因此没有意义).
这些字段旨在通知浏览器最大年龄; cookie的路径等,但浏览器不会将此信息发送回服务器.唯一一个拥有正确的最大年龄,路径等的重要时刻是创建cookie并将其添加到响应中.使用浏览器检查它是否存储了正确的信息,而不是尝试在服务器端找到它.
| 归档时间: |
|
| 查看次数: |
2293 次 |
| 最近记录: |