The forward method of the RequestDispatcher interface may be called by the
calling servlet only when no output has been committed to the client. If output data
exists in the response buffer that has not been committed, the content must be
cleared before the target servlet�s service method is called.
What should happen if I execute the following code:
where out is PrintWriter and dispatcher is RequestDispatcher.
With your code, it is likely that the response will not be committed before the forward is called. In that case, the RequestDispatcher is responsible for clearing the writer's buffer before passing the request/response forward.
Only if you're dangerously curious, read on.
There's also a bit of a catch (for us, not the container makers) here. If the response is committed (meaning something got flushed), then you'd get an IllegalStateException. It's possible that a flush can occur even without explicitly calling flush()!!!
One possibility... PrintWriter (in servlets) can be created with an autoFlush value that flushes the output on every println statement. I doubt if any containers set this to true for PrintWriters (or, if they do, they might be returning a container-specific subclass of PrintWriter that treats that flag differently), but servlet spec doesn't say that they won't.
Also... JspWriter (in JSPs) can be created with an "autoFlush" flag that defaults to true (you can change it with the page directive). According to the JSP spec, the autoFlush here doesn't run on every println() call - instead it flushes only when the buffer's size has been exceeded (the buffer can also be changed with the page directive and the container maker is required to default it to no less than 8kb). If this were your scenario and your code had lots of previous println statements and they overfilled the buffer, the buffer would force a flush. But RequestDispatcher in a JSP breaks MVC principles anyway, so you really should never use it in a JSP.
Lesson learned: When using RequestDispatcher in the real world make sure it's the first thing run (filters are often a great place for them!). There's no good reason why it shouldn't be. The exam will probably only test you on knowing that the forward method following a flush method will cause an IllegalStateException, so you won't have to worry too much about this gray area of "I didn't call flush is it still ok?"
This response is based on my own research. If anyone sees that I have made a false statement, feel free to correct me.
[ February 28, 2007: Message edited by: Marc Peabody ]