In Section 15.3.2.3 Supported handler method arguments and return types of the Spring 3.0 documentation, it says that a java.io.OutputStream or java.io.Writer can be specified as a parameter of a method annotated with @RequestMapping "for generating the response's content. This value is the raw OutputStream/Writer as exposed by the Servlet API." Is it the method's responsibility to close the writer before it finishes or should it remain open and some other Spring process will close it?
Asked
Active
Viewed 1,124 times
6
-
Since these streams are obtained from the Servlet API, see http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter – axtavt Dec 10 '10 at 17:55
-
possible duplicate of [Should I close the servlet outputstream ?](http://stackoverflow.com/questions/1829784/should-i-close-the-servlet-outputstream) – BalusC Dec 11 '10 at 01:55
2 Answers
3
It should leave it alone. As a general rule of thumb, if your code didn't open it, then it shouldn't close it, either.
In this case, the servlet container (not Spring) is responsible for flushing and closing all streams.
You could do it yourself, I doubt it would do any harm, but there's no need to do so.

skaffman
- 398,947
- 96
- 818
- 769
-
Ok, I shouldn't close the stream provided by spring, but what if I use a pipe, i.e. CSVWriter writer = new CSVWriter(springWriter); writer.writeLine("blabla"); If I don't close the writer (or at least flush it) I may lose any work, since it is done in some kind of buffer. – Vadim Kirilchuk Dec 07 '15 at 14:27
1
skaffman's correct, you don't have to close it, and in fact probably shouldn't, but it's still a good idea to flush() it, especially in a 'finally' clause if you're dealing with code that throws exceptions, ie exporting from a database.

Alex Marshall
- 10,162
- 15
- 72
- 117