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 why should we set response.setContentType before using PrintWriter or OutputStream? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Servlets
Reply Bookmark "why should we set response.setContentType before using PrintWriter or OutputStream?" Watch "why should we set response.setContentType before using PrintWriter or OutputStream?" New topic
Author

why should we set response.setContentType before using PrintWriter or OutputStream?

akash kumar
Ranch Hand

Joined: Jun 13, 2007
Posts: 63
why should we set response.setContentType before using PrintWriter or OutputStream?
Lorand Komaromi
Ranch Hand

Joined: Oct 08, 2009
Posts: 276
akash kumar wrote:why should we set response.setContentType before using PrintWriter or OutputStream?


You have to tell the browser what kind of data are you sending so that it can handle it appropriately...


OCJP 6 (93%)
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12265
    
    1
Obviously you can't set response headers if the response output stream has been flushed.

Now you might think that writing is safe because the output buffer would hold some characters before flushing - that way lies very mysterious future bugs.

Bill

Java Resources at www.wbrogden.com
akash kumar
Ranch Hand

Joined: Jun 13, 2007
Posts: 63
William Brogden wrote:Obviously you can't set response headers if the response output stream has been flushed.

Now you might think that writing is safe because the output buffer would hold some characters before flushing - that way lies very mysterious future bugs.

Bill



Does it mean the web server starts sending the results to the browser even before the doGet or doPost methods are returned?
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12265
    
    1
Does it mean the web server starts sending the results to the browser even before the doGet or doPost methods are returned?


Absolutely!

Thats why, if your application has to sent a content-length header, you have to provide your own buffering or temporary file scheme while you build the complete response.

Bill
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: why should we set response.setContentType before using PrintWriter or OutputStream?
 
Similar Threads
Is setContentType() optional?
PrintWriter vs OutputStream
Error while displaying PDF from IE
Setting response headers before returning content
About PrintWriter with println and write