This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in servlet regarding getWriter() and output stream.

 
sriram sundararajan
Ranch Hand
Posts: 43
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. When we will use addHeader method of response object?

2. Why servlet container is throwing IllegalStateException when am using both getWriter() and getOutputStream? Why can't i use both?

3. In a servlet am using res.getOutputStream() to write anything in the browser instead of PrintWriter.
In the same servlet am including one jsp. In the jsp i am using a implicit object 'out' to print something. The container throws illegal state exception in this scenario. If i am replacing the res.getOutputStream() with res.getWriter() in the servlet, it is not throwing any exception. What could be the reason?
 
Alexandre Cervieri
Greenhorn
Posts: 27
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Sriram,

I'm just starting to sudy for SCWCD, but anyway I'll try to answer your questions. I hope someone will read and correct if I'm wrong.

1: We use setHeader when defining the value of some HTTP header attribute. When some HTTP attribute allows multiple values (unfortunatelly I don't know an example of this) you should use addHeader to add the additional values.

2,3: The IllegalStateException exception is supposed to be thrown when you try to use both the PrinterWriter and the OutputStream objects. PrinterWriter is recommended to be used for text output, and OutputStream to generate binary output. I know that someone has a better and complete explanation for the reasons why one object should be used for text and the other for binary, but this is what I read in a online tutorial.
Maybe this is enough to answer the certification questions

Regards,

Alexandre.
 
Sergey Tyulkin
Ranch Hand
Posts: 87
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. One example of using headers is special last modified header. Browser can read the value of the header, check it with its cache and do not download any contents, if it already has current version of the resource
2. This behaviour is defined in specification. Simply put, writer is for text, OutputStream - for binary data.
3. Jsp you include (and all jsps in general) uses writer to writeOut its result. And if your servlet uses OutputStream you cannot switch to Writer - see p. 2.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic