java - 我需要刷新 servlet 输出流吗?

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

最佳答案

你不需要。 servlet 容器将为您刷新并关闭它。顺便说一句,close 已经隐式调用了flush。

另见 Servlet 3.1 specification 的第 5.6 章:

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:

  • 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 通常只有当您在同一流上有多个写入程序并且您想要切换写入程序(例如具有混合二进制/字符数据的文件),或者当您想要保留流指针在不确定的时间内打开(例如日志文件)。

关于java - 我需要刷新 servlet 输出流吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5043657/

相关文章:

java - 如何在excel中插入hashMap来绘制图表

java - 将 JSON 默认标记映射到 java 变量

java - 未加权无向图中的最长路径

javascript - 特殊字符 '\u0098' 使用 charCodeAt() 读取为 '\u02dc'

java - 如果流没有手动关闭,什么时候关闭?

java - ListView 中的按钮不可点击

java - 将 html 页面设置为 servlet 响应

java - Servlet 3.0 测试查询中的异步属性

android - 手机和PC之间的Android聊天

java - 将 OutputStream 转换为 ByteArrayOutputStream