Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should one call .close() on HttpServletResponse.getOutputStream()/.getWriter()?

In Java Servlets, one can access the response body via response.getOutputStream() or response.getWriter(). Should one call .close() on this OutputStream after it has been written to?

On the one hand, there is the Blochian exhortation to always close OutputStreams. On the other hand, I don't think that in this case there is an underlying resource that needs to be closed. The opening/closing of sockets is managed at the HTTP level, to allow things like persistent connections and such.

like image 747
Steven Huwig Avatar asked Jul 21 '09 13:07

Steven Huwig


People also ask

Should I close HttpServletResponse Outputstream?

The general rule of them is this: if you opened the stream, then you should close it. If you didn't, you shouldn't. Make sure the code is symmetric. In the case of HttpServletResponse , it's a bit less clear cut, since it's not obvious if calling getOutputStream() is an operation that opens the stream.

Do I need to close ServletOutputStream?

No you don't need to close it.

What is the purpose of the getWriter () method of ServletResponse?

getWriter. Returns a PrintWriter object that can send character text to the client. The PrintWriter uses the character encoding returned by getCharacterEncoding() .

What does Response getOutputStream do?

getOutputStream. Returns a ServletOutputStream suitable for writing binary data in the response. The servlet container does not encode the binary data. Calling flush() on the ServletOutputStream commits the response.


1 Answers

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.

like image 181
Nemi Avatar answered Sep 23 '22 09:09

Nemi