Search code examples
javaservletscookiestomcat8

Cannot set servlet cookies using Tomcat


I have the following code running as part of a custom filter:

Cookie cookie = new Cookie("NAME", "VALUE");
cookie.setMaxAge(Integer.MAX_VALUE);
response.addCookie(cookie);

When running UT using Jetty server I receive the cookie successfully from the servlet. Nevertheless, when I'm running a local Tomcat server (using IntelliJ), the cookie is not even set on the server side (i.e. not a client issue). The only cookie I can see is the jsessionid cookie.

I tried the following with no luck:

  1. setDomain("")
  2. setPath("/")
  3. response.flushBuffer() after adding the cookie.

I'm printing all the response cookies right after I added the new cookie, but my cookie is not listed.

Collection<String> headers = ((HttpServletResponse) res).getHeaders("Set-Cookie");
for (String header : headers) {
    System.out.println("Session Cookie:" + header);
}

I'm pretty new to web application and Java in general, so it is also possible that I missed something very basic. Will appreciate any help here.


Solution

  • I found the answer here: http://www.coderanch.com/t/577383/jforum/response-addCookie-work-filter.

    In short: "Adding a cookie requires modifying the HTTP headers of the response. Once the response has been "committed", e.g. anything written to the output stream, you can not modify the HTTP headers. The response has been committed by the time you try to add your cookie...Most JSP implimentations and some servlets will actually generate the response in a buffer. This means the response isn't committed the output is closed or manually flushed. So, this would work in some applications and not in others".

    Bottom line, I needed to update the response before the chain.doFilter(req, res) has been called.