3 thoughts on “How does getWriter() function in an HttpServletResponse?

  1. user

    Also note that several open source implementations of the Servlet API is available. This allows you to see how it can be done.

    I believe the official implementation has been open sourced too, and is included with the Glassfish server.

    Reply
  2. user

    One fairly simple implementation:

    PrintWriter getWriter() throws java.io.IOException {
          return new PrintWriter(socket.getOutputStream());
    }
    
    Reply
  3. user

    It doesn’t make a connection to the browser – the browser has already made a connection to the server. It either buffers what you write in memory, and then transmits the data at the end of the request, or it makes sure all the headers have been written to the network connection and then returns a PrintWriter which writes data directly to that network connection.

    In the buffering scenario there may be a fixed buffer size, and if you exceed that the data written so far will be “flushed” to the network connection. The big advantage of having a buffer at all is that if something goes wrong half-way through, you can change your response to an error page. If you’ve already started writing the response when something goes wrong, there’s not a lot you can do to indicate the error cleanly.

    (There’s also the matter of transmitting the content length before any of the content, for keep-alive connections. If you run out of buffer before completing the response, I’m reliably informed that the response will use a chunked encoding.)

    Reply

Leave a Reply

Your email address will not be published.