Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

PrintWriter in servlet and JSP

 
Ranadhir Nag
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ?
 
Ranadhir Nag
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13061
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic