HttpServletResponse输入输出流是否需要flush close

1,是否需要 close the servlet outputstream?

Normally you should not close the stream. The servlet container will automatically close the stream after the servlet is finished running as part of the servlet request life-cycle.

For instance, if you closed the stream it would not be available if you implemented a Filter.

Having said all that, if you do close it nothing bad will happen as long as you don't try to use it again.

EDIT: another filter link

EDIT2: adrian.tarau is correct in that if you want to alter the response after the servlet has done its thing you should create a wrapper extending HttpServletResponseWrapper and buffer the output. This is to keep the output from going directly to the client but also allows you to protect if the servlet closes the stream, as per this excerpt (emphasis mine):

A filter that modifies a response must usually capture the response before it is returned to the client. The way to do this is to pass the servlet that generates the response a stand-in stream. The stand-in stream prevents the servlet from closing the original response stream when it completes and allows the filter to modify the servlet's response.

Article

One can infer from that official Sun article that closing the outputstream from a servlet is something that is a normal occurrence, but is not mandatory.


2,是否需要 flush the servlet outputstream?

You don't need to. The servletcontainer will flush and close it for you. The close by the way already implicitly calls flush.

See also chapter 5.6 of Servlet 3.1 specification:

扫描二维码关注公众号,回复: 865166 查看本文章

5.6 Closure of Response Object

When a response is closed, the container must immediately flush all remaining content in the response buffer to the client. The following events indicate that the servlet has satisfied the request and that the response object is to be closed:

  • The termination of the service method of the servlet.
  • The amount of content specified in the setContentLength or setContentLengthLongmethod of the response has been greater than zero and has been written to the response.
  • The sendError method is called.
  • The sendRedirect method is called.
  • The complete method on AsyncContext is called.

Calling flush while still running the servlet's service is usually only beneficial when you have multiple writers on the same stream and you want to switch of the writer (e.g. file with mixed binary/character data), or when you want to keep the stream pointer open for an uncertain time (e.g. a logfile).

转载自:

https://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter

https://stackoverflow.com/questions/5043657/do-i-need-to-flush-the-servlet-outputstream

猜你喜欢

转载自blog.csdn.net/vip_wangsai/article/details/78357018