Originally posted by john guthrie:
chapter 5 question 1 asks which methods can often lead to an IllegalStateException when using a RequestDispatcher. the answer given is flush, but i'd've thought that any method that gets you started down the road of writing a response would be part of the answer, so i included getOutputStream and write. i'd especially include write, because if the servlet is using small buffers, the write could cause a flush in itself, yes?
Hi John,
This question is very similar to the one in your other post. I have included my answer to that question here:
There are deeper issues here that I would like to explain so you have a deeper understanding of what the container is doing. Clearly the response object (HttpServletResponse) has two aspects: headers and body. If you start writing to the body (via getWriter or getOutputStream) before setting your headers, then you run the risk that the response object's body buffer becomes full and is sent to the client. If that happens, then when you attempt to set a header or setContentType these methods will throw an IllegalStateException. Why? Because the headers must appear at the beginning of the HTTP stream, but your servlet has already commited the headers when the body buffer was flushed. Make sense? Your hunch that the write() method
might cause the buffer to flush is correct, but remember that options must be valid under
all circumstances and because writing only one byte is not likely to fill the buffer, then this option is not valid. The only valid option is the flush() method.
Cheers,
Bryan