Why can't I update the HttpServletResponse headers AFTER calling getWriter ()?

I figured out on the Internet after fixing the problem in the afternoon @, where Cookies added to the HttpServletResponse were not properly reflected in the response headers because our Servlet already received a PrintWriter response (i.e. response.getWriter () ) before we add cookies. Now I know that best practices dictate that changes to the response header (i.e. setting the type of content, adding / editing cookies, etc.) should be done before getWriter () is called, but I'm looking for: why?

We wondered why extracting PrintWriter actually freezes response headers, but why does the final servlet specification provide this?

+6
source share
2 answers

Section SRV.5.2 Headers for Java โ„ข Version Servlet Specification Version 2.4

To be successfully transferred to the client, headers must be set before the response is complete. The headers set after the response will be ignored by the servlet container.

Thus, the specification does not explicitly mention getWriter() , which affects header settings.

However, the implementation of your servlet container can be selected to handle the response as incoming after calling getWriter() . This is a little different.

In some containers that I worked with, you get a warning that is logged when you try to set the header after the response is completed.

You should always call getWriter() as late as possible, as you may need to set the character encoding, etc. that must be set before calling getWriter() .

+11
source

Because the headers precede the body in HTTP. That's why they are called "headlines." If you call getWriter (), you write to the body, so itโ€™s too late to start changing the values โ€‹โ€‹of the response headers later.

+3
source

Source: https://habr.com/ru/post/909694/


All Articles