我需要刷新servlet输出流吗?

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

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

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。

另请参见Servlet 3.1规范的第5.6章:

5.6关闭响应对象

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

  • 终止servlet的service方法。
  • 响应的setContentLengthsetContentLengthLong方法中指定的内容量已大于零并已写入响应。
  • 调用sendError方法。
  • 调用sendRedirect方法。
  • 调用AsyncContext上的complete方法。

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

猜猜你在其他问题中得到的答案同样如此:如果是你的流,请冲洗并关闭它。 除非另有说明,否则流创建者应该这样做。

要指出“不需要刷新”规则的一个潜在的例外:使用IBM WebSphere Application Server并使用响应Writer (而不是OutputStream ),我发现我必须刷新它; 否则我的回复数据的最后一部分丢失了。 我想IBM的HttpServletResponse类确实刷新了OutputStream,但为Writer使用了一个单独的缓冲区,并没有刷新它。 其他应用程序服务器似乎这样做。

因此,如果您将响应数据发送给Writer ,则刷新它会更安全。 但是没有必要将OutputStream刷新到讨价还价中。

(我会把它作为评论发布,但缺乏声誉。)

 java.lang.Object extended byjava.io.Writer extended byjavax.servlet.jsp.JspWriter close public abstract void close() throws IOException Close the stream, flushing it first. This method needs not be invoked explicitly for the initial JspWriter as the code generated by the JSP container will automatically include a call to close(). Closing a previously-closed stream, unlike flush(), has no effect. Throws: IOException - If an I/O error occurs ============================ So, DO NOT close the output stream explicitly.