简体   繁体   中英

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?

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. When the servlet than has generated the response i can catch the outgoing response and work with it again.

在此处输入图片说明

What i have done, is on the request determined that the specific cookie isin't present so i set a boolean value representing this. Than when the response returns from the servlet i add the specific 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. 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. I dont have any browser settings that deny new cookies and i get the JSESSIONID cookie without problems.

Cookies are set in HTTP headers. 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. 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).

I strongly suspect the response is committed by the time you try and add the cookie so the call is simply ignored.

The simple solution is to move the call to addCookie() to before the call to chain.doFilter(httpRequest, httpResponse);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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