wood burning stoves 2.0*
The moose likes Servlets and the fly likes PrintWriter in servlet and JSP Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Servlets
Bookmark "PrintWriter in servlet and JSP" Watch "PrintWriter in servlet and JSP" New topic
Author

PrintWriter in servlet and JSP

Ranadhir Nag
Ranch Hand

Joined: Mar 09, 2006
Posts: 138
Read a statement in a JSP-related article recently:
"response object is the HttpServletResponse associated with the response to the client. Note that, since the output stream (see out below) is buffered, it is legal to set HTTP status codes and response headers, even though this is not permitted in regular servlets once any output has been sent to the client. "
What this indicates is that the PrintWriter object in servlet is not buffered.
But as far as i know the following code in servlet is legal:
// Get the output stream
PrintWriter out = response.getWriter();//THIS IS A RESPONSE COMMIT
// Set the content type
response.setContentType("text/plain");
// Set the "custom" headers:
response.setHeader(
"Stat","Striving hard");
// Send the data
out.print(data.toString());
out.flush();
Did i misinterpret the article?What then exactly is the difference in the default response object in JSP and servlet,as far as output stream is concerned?
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

Did i misinterpret the article?

I think you did First, I can't understand the comment "THIS IS A RESPONSE COMMIT". What does it mean ?
Anyway,
1. You get the response's writer
2. You set a few headers
3. You write to the response
4. You flush
According to your article, this is ok.

What would happen if you'd try the following : 1,3,4,2 ?


[My Blog]
All roads lead to JavaRanch
Ranadhir Nag
Ranch Hand

Joined: Mar 09, 2006
Posts: 138
So,i understand that in JSP response.getwriter returns the JSPwriter which is a buffer enabled printwriter which allows the 1,3,2,4 sequence to work in JSP.
Is there any way this can be done in servlet?
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12792
    
    5
If you want to write to the response before setting headers, you are taking a chance that the response buffer will not be flushed.

If you will consult the JavaDocs for the HttpServletResponse and ServletResponse classes, you will note the setBufferSize method - read that material.

Bill
 
GeeCON Prague 2014
 
subject: PrintWriter in servlet and JSP