File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Servlets and the fly likes PrintWriter in servlet and JSP Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of Mongo DB Applied Patterns this week in the MongoDB forum
or a resume review from Five Year Itch in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Servlets
Reply 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: 137
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: 14669
    
  11

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: 137
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: 12265
    
    1
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


Java Resources at www.wbrogden.com
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: PrintWriter in servlet and JSP
 
Similar Threads
JSP page strange Output
some confusion
JSP Page doubt?
HttpServletResponse.getWriter
How To open a file in JSP