在 Java Servlet 中,可以通过 response.getOutputStream()
或 response.getWriter()
访问响应正文。是否应该在写入此 OutputStream
后调用 .close()
?
一方面,Blochian 劝告总是关闭 OutputStream
s。另一方面,我不认为在这种情况下存在需要关闭的底层资源。套接字的打开/关闭在 HTTP 级别进行管理,以允许诸如持久连接之类的事情。
最佳答案
通常您不应关闭流。作为 servlet 请求生命周期的一部分,servlet 容器将在 servlet 完成运行后自动关闭流。
例如,如果您关闭了流,如果您实现了 Filter,它将不可用。 .
说了这么多,如果你关闭它,只要你不尝试再次使用它,什么都不会发生。
EDIT2:adrian.tarau 是正确的,如果你想在 servlet 完成它的事情后改变响应,你应该创建一个扩展 HttpServletResponseWrapper 的包装器并缓冲输出。这是为了防止输出直接发送到客户端,但也允许您保护 servlet 是否关闭流,根据以下摘录(强调我的):
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.
从那篇 Sun 官方文章中可以推断,从 servlet 中关闭 OutputStream
是正常现象,但不是强制性的。
关于java - 是否应该在 HttpServletResponse.getOutputStream()/.getWriter() 上调用 .close()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1159168/