我需要刷新servlet输出流吗? [英] Do I need to flush the servlet outputstream?

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

问题描述

我是否需要从HttpServletResponse中刷新OutputStream?

Do I need to "flush" the OutputStream from the HttpServletResponse?

我已经看到我应该关闭servlet输出流吗?我不需要关闭它,但是我不清楚是否需要刷新它。我也应该从容器中得到它吗?

I already saw from to Should I close the servlet outputstream? that I don't need to close it, but it's not clear if I need to flush it. Should I expect it from the container as well?

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
   throws ServletException, IOException {
   byte[] response = getResponse();
   String responseType = getResponseType();

   response.setContentLength(response.length);
   response.setContentType(responseType);
   response.getOutputStream().write(response);
   response.getOutputStream().flush(); // yes/no/why?
}


推荐答案

你不需要。 servletcontainer将为您刷新并关闭它。顺便说一下,已经隐式调用flush。

You don't need to. The servletcontainer will flush and close it for you. The close by the way already implicitly calls flush.

另见 Servlet 3.1规范


5.6关闭响应对象



当响应关闭时,容器必须立即将响应缓冲区中剩余的
内容刷新到客户端。以下事件表明servlet已满足请求并且响应对象将被关闭:

5.6 Closure of Response Object

When a response is closed, the container must immediately flush all remaining content in the response buffer to the client. The following events indicate that the servlet has satisfied the request and that the response object is to be closed:


  • 终止 service servlet方法。

  • setContentLength 或$中指定的内容量b $ b setContentLengthLong 响应方法大于零,并且已将
    写入响应。

  • 调用 sendError 方法。

  • 调用 sendRedirect 方法。

  • 调用 AsyncContext 上的完整方法。

  • The termination of the service method of the servlet.
  • The amount of content specified in the setContentLength or setContentLengthLong method of the response has been greater than zero and has been written to the response.
  • The sendError method is called.
  • The sendRedirect method is called.
  • The complete method on AsyncContext is called.

在仍然运行servlet的服务时调用flush通常只有在同一个流上有多个写入器并且要切换时才有用写入程序(例如,具有混合二进制/字符数据的文件),或者当您希望将流指针保持打开一段不确定的时间时(例如日志文件)。

Calling flush while still running the servlet's service is usually only beneficial when you have multiple writers on the same stream and you want to switch of the writer (e.g. file with mixed binary/character data), or when you want to keep the stream pointer open for an uncertain time (e.g. a logfile).

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

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