我是否需要刷新 servlet 输出流? [英] Do I need to flush the servlet outputstream?
问题描述
我是否需要从 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 将为您刷新并关闭它.顺便说一下,close 已经隐式调用了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:
- servlet 的
service
方法的终止. setContentLength
中指定的内容量或setContentLengthLong
方法的响应已经大于零并且已写入回复.sendError
方法被调用.sendRedirect
方法被调用.- 调用
AsyncContext
上的complete
方法.
- The termination of the
service
method of the servlet. - The amount of content specified in the
setContentLength
orsetContentLengthLong
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 onAsyncContext
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屋!