应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()吗? [英] Should one call .close() on HttpServletResponse.getOutputStream()/.getWriter()?

查看:516
本文介绍了应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到谷歌的一些权威答案。在Java servlet中,可以通过response.getOutputStream()或response.getWriter()访问响应主体。是否应该在写入之后在此流上调用.close()?

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?

一方面,Blochian劝告总是关闭输出流。另一方面,我认为在这种情况下不存在需要关闭的底层资源。套接字的打开/关闭是在HTTP级别进行管理,以允许诸如持久连接之类的东西。

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.

推荐答案

通常你应该不要关闭流。作为servlet请求生命周期的一部分,servlet完成运行后,servlet容器将自动关闭流。

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.

编辑:另一个过滤器链接

EDIT2:adrian.tarau是正确的,如果你想改变在servlet完成它之后的响应你应该创建一个包装器来扩展HttpServletResponseWrapper并缓冲输出。这是为了保持输出不直接进入客户端,但也允许你保护servlet关闭流,如下摘录(强调我的):

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):


修改响应的过滤器必须
通常
返回给客户端之前捕获响应。
这样做的方法是传递
生成响应的servlet一个替换
流。替代流阻止
servlet在完成时关闭原始
响应流,
允许过滤器修改
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关闭输出流是正常现象,但不是强制性的。

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.

这篇关于应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆