【发布时间】:2018-08-31 01:27:53
【问题描述】:
我的问题是:如何通过过滤器设置一个尚不存在的 cookie?
根据我了解过滤器的工作原理,我可以在传入的请求到达给定的 servlet 之前捕获它,处理该请求并将其传递给 servlet。当 servlet 生成响应后,我可以捕获传出响应并再次使用它。
我所做的是根据请求确定特定的 cookie 不存在,所以我设置了一个布尔值来表示它。当响应从 servlet 返回时,我添加了特定的 cookie。
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
ServletContext sc = filterConfig.getServletContext();
//Run when receiving the request from the client
boolean cookie = false;
System.out.println("Searching for the cookie (request)");//debug
Cookie[] cookies = httpRequest.getCookies();
if(cookies != null) {
for(int a = 0; a < cookies.length; a++) {
if(cookies[a].getName().equals("PositionCookie")) {
cookie = true;
}
}
}
chain.doFilter(httpRequest, httpResponse);
//Run when sending the response to the client
System.out.println("Determining to create cookie (response)");//Debug
if(!cookie) {
System.out.println("Creating 'PositionCookie' (response)");//debug
Cookie c = new Cookie("PositionCookie", "/test/data/string");
c.setPath("/");
c.setMaxAge(-1);
httpResponse.addCookie(c);
}
}
因为我只是希望这是一个会话 cookie,所以我给它的 MaxAge 为 -1。 所有调试行都被激活并写入 catalina.out,所以我知道新的 Cookie 语句已经到达,但新的 cookie 没有添加到浏览器保存的 cookie 中。我没有任何拒绝新 cookie 的浏览器设置,并且我得到 JSESSIONID cookie 没有问题。
【问题讨论】:
-
可以禁用浏览器 cookie。