Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Do I need to "flush" the OutputStream from the HttpServletResponse?

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?
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
326 views
Welcome To Ask or Share your Answers For Others

1 Answer

You don't need to. The servletcontainer will flush and close it for you. The close by the way already implicitly calls flush.

See also chapter 5.6 of Servlet 3.1 specification:

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.

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...