我需要刷新servlet输出流吗?

时间:2011-02-18 16:10:37

标签: java servlets outputstream

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

我已经从Should I close the servlet outputstream?看到我不需要关闭它,但我不清楚是否需要冲洗它。我也应该从容器中预期它吗?

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?
}

4 个答案:

答案 0 :(得分:48)

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

另见Servlet 3.1 specification的第5.6章:

  

5.6关闭响应对象

     

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

     
      
  • 终止servlet的service方法。
  •   
  • setContentLength或中指定的内容量   setContentLengthLong响应的方法大于零   已被写入回复。
  •   
  • 调用sendError方法。
  •   
  • 调用sendRedirect方法。
  •   
  • 调用complete上的AsyncContext方法。
  •   

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

答案 1 :(得分:3)

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

答案 2 :(得分:1)

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

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

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

答案 3 :(得分:-1)

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.