本文介绍了我应该关闭servlet输出流吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是否负责关闭HttpServletResponse.getOutputStream()(或getWriter()甚至输入流)
或者我应该将它留给容器?

Am I responsible for closing the HttpServletResponse.getOutputStream() (or the getWriter() or even the inputstream)or should I leave it to the container ?

protected void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
    OutputStream o = response.getOutputStream();
    ...
    o.close(); //yes/no ?
}


推荐答案

你确实不需要这样做。

You indeed don't need to do so.

拇指规则:如果您没有使用新的SomeOutputStream()创建/打开它,那么你就不要不需要自己关闭它。如果它是例如新的FileOutputStream(c:/foo.txt),那么你显然需要自己关闭它。

Thumb rule: if you didn't create/open it yourself using new SomeOutputStream(), then you don't need to close it yourself. If it was for example a new FileOutputStream("c:/foo.txt"), then you obviously need to close it yourself.

有些人仍然这样做的原因只是确保不会再将任何内容写入响应正文。如果它会发生,那么这将在appserver日志中导致 IllegalStateException ,但这不会影响客户端,因此客户端仍然会得到正确的响应。这也是一个更容易的调试,以发现请求 - 响应链中的潜在问题,乍看之下您将看不到这些问题。例如,其他东西会向链中更深处的响应主体追加更多数据。

Reasons that some people still do it are just to ensure that nothing more will be written to the response body. If it would ever happen, then this will cause an IllegalStateException in the appserver logs, but this wouldn't affect the client, so the client still gets the proper response. This is also an easier debug to spot the potential problems in the request-response chain which you wouldn't see at first glance. For example, something else is appending more data to the response body somewhere further down in the chain.

您在初学者中看到的另一个原因是他们只是想要阻止将更多数据写入响应正文。当JSP错误地在响应中扮演角色时,您经常会看到这种情况。他们只是忽略日志中的 IllegalStateException 。不用说,这个特殊目的是

Another reason which you see among starters is that they just wanted to prevent that more data is written to the response body. You see this often when JSP incorrectly plays a role in the response. They just ignore the IllegalStateExceptions in the logs. Needless to say that this particular purpose is bad.

这篇关于我应该关闭servlet输出流吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 08:07
查看更多