Why can't HttpServletResponse Headers be updated AFTER getWriter() is called?

后端 未结 2 428
攒了一身酷
攒了一身酷 2021-01-12 07:36

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 respons

2条回答
  •  梦毁少年i
    2021-01-12 08:13

    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.

提交回复
热议问题