简体   繁体   English

Java JSP过滤器,如果不存在则设置cookie

[英]Java JSP filter, set cookie if not exist

My question is: How can i set a cookie that does not already exist through a filter? 我的问题是:如何设置通过过滤器尚不存在的Cookie?

As i understand how filters work i can catch an incoming request before it reaches a given servlet, work on the request and pass it to the servlet. 当我了解过滤器如何工作时,我可以在传入请求到达给定servlet之前捕获它,处理该请求并将其传递给servlet。 When the servlet than has generated the response i can catch the outgoing response and work with it again. 当servlet生成响应时,我可以捕获传出的响应并再次使用它。

在此处输入图片说明

What i have done, is on the request determined that the specific cookie isin't present so i set a boolean value representing this. 我所做的是,在请求中确定特定的cookie不存在,因此我设置了一个代表此值的布尔值。 Than when the response returns from the servlet i add the specific 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);
    }
}

Since i just want this to be a session cookie i have given it a MaxAge of -1. 由于我只希望它成为会话cookie,所以我给它设置了MaxAge -1。 All the debug lines are activated and written to catalina.out so i know that new Cookie statement has been reached but a new cookie is not added to the browsers saved cookies. 所有的调试行均被激活并写入catalina.out,因此我知道已达到新的Cookie语句,但未将新的cookie添加到浏览器保存的cookie中。 I dont have any browser settings that deny new cookies and i get the JSESSIONID cookie without problems. 我没有任何拒绝新cookie的浏览器设置,并且我得到了JSESSIONID cookie,没有任何问题。

Cookies are set in HTTP headers. Cookies在HTTP标头中设置。 The headers are the first thing that are written as part of the response. 标头是作为响应的一部分写入的第一件事。 The Servlet container only buffers so much of the response before writing it (headers first) to the client. Servlet容器在将响应写到客户端之前(先标头)仅缓冲大量响应。 Once the headers have been written the response is considered to be committed. 标头一旦写入,就认为响应已提交。 (The application can also force the commit of the response.) Once the response has been committed cookies cannot be added (since the HTTP headers have already been sent to the client). (应用程序还可以强制提交响应。)一旦提交了响应,就无法添加cookie(因为HTTP标头已经发送到客户端)。

I strongly suspect the response is committed by the time you try and add the cookie so the call is simply ignored. 我强烈怀疑在尝试添加cookie时是否已提交响应,因此该调用将被忽略。

The simple solution is to move the call to addCookie() to before the call to chain.doFilter(httpRequest, httpResponse); 简单的解决方案是addCookie()的调用移到对chain.doFilter(httpRequest, httpResponse);的调用之前chain.doFilter(httpRequest, httpResponse);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM