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

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.

Leave a Comment