views:

481

answers:

2

Hi,

I have observed that while RequestDispatcher.forward(request, response) can throw an IllegalStateException (if the response is committed) , RequestDispatcher.include(request, response) does not throw an IllegalStateException(even if the response was committed before).

I have verified this on Tomcat 6.0.20.

I am aware that the include() method does not declare that an IllegalStateException can be thrown, but it's still an after-thought.

Any ideas on why was the servlet-api designed this way ? IMHO, if a response has been committed, no further forwarding/including should be allowed.

+1  A: 

The include just adds more info to the response. It doesn't matter if it is already committed or not. A forward (and a redirect) simply requires a blank and clean response because it is to be used by the target exclusively.

BalusC
In that case, that brings up the question of what does a "committed response" mean ? According to my understanding, a committed response is one whose OutputStream has been flushed. Why then, do include() and forward() behave differently for committed responses ? (include() does not throw an exception even if the response is committed).Thanks for the reply.
divesh premdeep
The include just **adds** data to the current response. The forward/redirect requires a **blank** response. Do you see it now? Once a response is committed there is absolutely no point of return. The bytes are already sent to the client.
BalusC
+3  A: 

Include would be useless if it throws IllegalStateException like Forward. The common use case is to write part of page in the servlet, then include other part from another resource. So the response is most likely already started or committed.

If you look at the implementation, Include doesn't care about the state of the original response because it uses a brand new wrapped response. After returning from the included resource, the body from wrapped response is appended to the original response. While forward uses the same response so it must be untouched.

ZZ Coder
That explains it. Thanks !
divesh premdeep