我需要从 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
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 通常只有当您在同一流上有多个写入程序并且您想要切换写入程序(例如具有混合二进制/字符数据的文件),或者当您想要保留流指针在不确定的时间内打开(例如日志文件)。
关于java - 我需要刷新 servlet 输出流吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5043657/