Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does getWriter() function in an HttpServletResponse?

Tags:

java

servlets

In the method service(), we use

PrintWriter out = res.getWriter();

Please tell me how it returns the PrintWriter class object, and then makes a connection to the Browser and sends the data to the Browser.

like image 282
pratap Avatar asked Apr 15 '09 06:04

pratap


1 Answers

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

like image 59
Jon Skeet Avatar answered Sep 29 '22 23:09

Jon Skeet