tags:

views:

863

answers:

3

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.

+8  A: 

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

Jon Skeet
(Chunked encoding can handle the case where you need to have written out the headers before completing the buffering of contents.)
Tom Hawtin - tackline
@Tom: I thought that might be the case, but I wasn't sure. Will edit.
Jon Skeet
A: 

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.

Thorbjørn Ravn Andersen
A: 

One fairly simple implementation:

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