I’ve been digging around the web after fixing an issue this afternoon @ work where Cookies added to the HttpServletResponse weren’t being properly reflected in the response headers because our Servlet had already retrieved the response’s PrintWriter (i.e. response.getWriter()) before we added the cookies. I’m now aware that best practices dictate that response header modifications (i.e. setting content type, adding/editing Cookies, etc.) must be done prior to a call to getWriter() but, what I’m looking for is: Why?
We’ve been speculating about why retrieving the PrintWriter in effect freezes the response headers but why definitively does the Servlet specification enforce that?
Answer
Section SRV.5.2 Headers of the Java™ Servlet Specification Version 2.4
To be successfully transmitted back to the client, headers must be set before
the response is committed. Headers set after the response is committed will be
ignored by the servlet container.
So the spec doesn’t explicitly mention getWriter()
having an effect on setting headers.
However, your servlet container implementation may have chosen to treat the response as having been comitted once getWriter()
is called. That is subtly different.
In some of the containers I’ve worked with you get a warning logged when you attempt to set a header after the response has been comitted.
It is always worth calling getWriter()
as late as possible, as you may want the opportunity to set the character encoding, etc, which must be set before getWriter()
is called.