Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

contentType, PrintWriter Q?  RSS feed

 
rahul dighe
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In most of the examples i read,i see that u set the contentType before getting the Writer. is there a technical reason for this ?
i tried changing the order it still works ?.
response.setContentType("text/html");
PrintWriter out = response.getWriter();
 
Matthew Phillips
Ranch Hand
Posts: 2676
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is because the servlet buffers the response headers, but may not buffer the data that is sent back to the browser. That is why you need to set all of your headers before accessing your PrintWriter.
 
rahul dighe
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well the getWriter() is not same as sending an output back to the client. i understand the situation where you have all of your out.println() statements and then u set contentType, in which case ur content goes first before the headers, but how does it matter if i call res.setContentType before i get the writer.
As long as i dont' have out.println() statements why should it matter ??
 
Mike Curwen
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It would matter if you are also setting a charset with the content type.

From the API for getWriter(): The character encoding used is the one specified in the charset= property of the setContentType(java.lang.String) method, which must be called before calling this method for the charset to take effect.

the charset= property would be appended to the content type string like so:

text/html; charset=ISO-8859-4.

So there is at least one instance where it would not perform as expected if you reversed the orders of the calls.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!