【问题标题】:Java JSP filter, set cookie if not existJava JSP过滤器,如果不存在则设置cookie
【发布时间】: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。

标签: java jsp cookies filter


【解决方案1】:

Cookie 设置在 HTTP 标头中。标头是作为响应的一部分写入的第一件事。 Servlet 容器在将响应写入客户端之前(首先是标头)仅缓冲这么多响应。一旦标头被写入,响应就被认为已提交。 (应用程序也可以强制提交响应。)一旦提交了响应,就无法添加 cookie(因为 HTTP 标头已经发送到客户端)。

我强烈怀疑响应是在您尝试添加 cookie 时提交的,因此调用会被忽略。

简单的解决方案是将对addCookie()的调用移动到对chain.doFilter(httpRequest, httpResponse);的调用之前

【讨论】:

  • 正如您建议将 addCookie() 移动到 chain.doFilter() 方法解决它之前,但我不明白。如果过滤器可以向响应对象添加一些东西,那意味着它已经创建了..但是谁创建了它?我以为是 servlet 创建了响应,但在这里它是在到达 servlet 之前创建的。
  • 响应对象已经存在。 Servlet 只是填充它/写入它。在此之前没有什么能阻止过滤器对其进行写入。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-28
  • 1970-01-01
  • 1970-01-01
  • 2013-07-13
  • 2021-09-10
相关资源
最近更新 更多