Saturday, July 19, 2008

forward vs include of request dispatcher

Recently I was analyzing a web application along with my colleagues and came across an issue, which required us to be clear on the concepts of forward and include methods of RequestDispatcher. A brief on the application setup before I explain the problem and solution.

We have a filter, a servlet and a jsp. All requests coming for jsp shall go through the filter. Filter does a forward to servlet and then call the next one in the chain, which is jsp. With this setup we are getting the IllegalStateException when we invoke the jsp.

This issue helped to clear my basic understanding of forward & include. I always thought that with forward control does not come back to the invoker !! Wrong, control does come back.

Forward - control comes back to the invoker, but response shall be committed even if the invoked did not write anything to the output.

Include - control comes back to the invoker, but response shall not be committed. The invoked might add something to the response, to which invoker might add more.

Redirect - control does not come back to the invoker.

In our case the problem was after the forward call to the servlet from filter, response is committed. Then when the control reaches jsp, it is trying to create a session (we haven't disabled session creation) which is not allowed. To correct this we are creating the session before forwarding the request to the servlet so that when the control reaches the jsp, session shall be available.

No comments: