A servlet can not set the headers and cookies after writing data to the servlet's output stream. Once the servlet writes data, headers are committed. However CookieExample writes some data first before doing addCookie on the response. The reason why this code works at all even with the above bug is: The CookieExample is only writing a small amount of data before doing response.addCookie. That data is still held in buffer and not yet sent over the wire. Hence the headers are not yet committed. So it is pure luck that this example works. You can easily expose the bug by writing say 20K characters in this example before response.addCookie is called. You will see that the cookies that are adding to response are not actually sent back to client. Fix is simple. Move up the response.addCookie() before response.getWriter()
Well, I disagree. The buffer default size is specified in the spec (it's 2K I think). Hence, if you write a small amount of data, the response will not be committed and the cookies can be set reliably. You can also set the buffer size manually, BTW. So this will not be addressed; please do not reopen the report.
Here are some facts that may lead you to reconsider. - The servlet spec itself does not mandate a default size for the buffer. The user can call response.setBufferSize to set the buffer to any size. - The user can tweak the bufferSize attribute of coyote or the legacy connector in server.xml. There is nothing preventing user to set it to 0 in which case the cookie example immediately breaks. - Users tend to use these examples as base for something that they like to achieve. So it is a good idea to provide users with an example that is more robust and does not break depending on how much data they write or what settings they have in server.xml.
Well, I wasn't too happy with Remy's decision to mark this bug as invalid, either. Having thought about this for a while, I ended up with a list of facts almost identical to the one posted by Vichy. For an example refered to as a starting point for servlet developers and used as a source for copy&paste best effort should be made to use good coding practises. Therefore, I decided to reopen this bug. I am currently working on a patch which I will soon propose for discussion.
Created attachment 7033 [details] Proposed patch moving call to response.addCookie() before response.getWriter()
Fixed in 7.0.x for 7.0.6 onwards but too trivial to consider back-porting.