views:

1823

answers:

4

I couldn't find an authoritative answer to this with some Googling. In Java servlets, one can access the response body via response.getOutputStream() or response.getWriter(). Should one call .close() on this stream after it has been written to?

On the one hand, there is the Blochian exhortation to always close output streams. 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.

+8  A: 

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.

Nemi
This is correct. One thing to note is that in some cases you may need to flush the stream, and that is perfectly permissible.
toluju
+2  A: 

You should close the stream, the code is cleaner since you invoke getOutputStream() and the stream is not passed to you as a parameter, when usually you just use it and don't attempt to close it. The Servlet API doesn't states that if the output stream can be closed or must not be closed, in this case you can safely close the stream, any container out there takes care of closing the stream if it was not closed by the servlet.

Here is the close() method in Jetty, they close the stream if it not closed.

public void close() throws IOException
    {
        if (_closed)
            return;

        if (!isIncluding() && !_generator.isCommitted())
            commitResponse(HttpGenerator.LAST);
        else
            flushResponse();

        super.close();
    }

Also as a developer of a Filter you should not presume that the OutputStream is not closed, you should always pass another OutputStream if you want to alter the content after the servlet has done its job.

EDIT : I'm always closing the stream and I didn't had any problems with Tomcat/Jetty. I don't think you should have any problems with any container, old or new.

adrian.tarau
"You should close the stream, the code is cleaner..." - To me, code peppered with .close() looks less clean than code without, particularly if the .close() is unnecessary -- which is what this question is attempting to determine.
Steven Huwig
yep, but beauty comes after :)Anyway, since the API is not clear I would prefer to close it, the code looks consistent, once you request an OutputStream you should close it unless the API says "don't close it".
adrian.tarau
+3  A: 

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. The Javadoc just says that it "Returns a ServletOutputStream"; similarly for getWriter(). Either way, what is clear is that HttpServletResponse "owns" the stream/writer, and it (or the container) is responsible for closing it again.

So to answer your question - no, you should not close the stream in this case. The container must do that, and if you get in there before it, you risk introducing subtle bugs in your application.

skaffman
+1  A: 

If there is any chance the filter might be called on an 'included' resource, you should definitely not close the stream. This will cause the including resource to fail with a 'stream closed' exception.

Skip Head
Thanks for adding this comment. Hilariously enough I am still grappling with the problem a little bit -- just now I noticed NetBeans's servlet template does include code to close the output stream...
Steven Huwig