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

问题描述

在 Java Servlet 中,可以通过 response.getOutputStream()response.getWriter() 访问响应正文.是否应该在写入此 OutputStream 后调用 .close() ?

In Java Servlets, one can access the response body via response.getOutputStream() or response.getWriter(). Should one call .close() on this OutputStream after it has been written to?

一方面,Blochian 劝告总是关闭OutputStreams.另一方面,我不认为在这种情况下存在需要关闭的底层资源.套接字的打开/关闭在 HTTP 级别进行管理,以允许持久连接等.

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

另一个过滤器链接

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 的响应.

文章

可以从 Sun 的那篇官方文章中推断,从 servlet 中关闭 OutputStream 是一种正常现象,但不是强制性的.

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() 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 07:53
查看更多