Wednesday, October 26, 2005

If we try to forward a request with the help of RequestDispatcher after the response is committed(flush() method called) then we will get an IllegalStateException. This is fine because the response is already sent to the client and the request is a history.

This link has got good mention about forward and commit techniques.

But what will happen if I write something to the response output like

out.println("##");
RequestDispatcher dispatcher =
req.getRequestDispatcher("/servlet/aView");
dispatcher.forward(req, res);
out.println("!!");

and call RequestDispatcher before committing the response?

out.println("##");

"##" is stored in the output buffer (but not yet sent to the browser).

RequestDispatcher dispatcher =
req.getRequestDispatcher("/servlet/aView");
dispatcher.forward(req, res);

The output buffer is cleared, removing "##". Uncommitted output in the response buffer is automatically cleared before the forward.

Then "/servlet/aView" is called, its response is committed and the output stream is closed.

out.println("!!");

An IOException is thrown because "out" is closed.

The reason why you are not getting an IOException message or the output "!!" is because
after the request and response has been forwarded to the said url, the output stream will be closed there and nothing will be sent to the client anymore (Any exceptions thrown will be effectively invisible).

Thats why it is considered Best Practice to use return keyword after a request has been forwarded, using requestdispatcher.

RequestDispatcher rd = getServletContext().getRequestDispatcher("/jsp/ABC.jsp");
rd.forward(request, response);
return;

Check this thread for details.



0 Comments:

Post a Comment

<< Home