forward() is a method in RequestDispatcher interface which is used to dispatch the control from a servlet to another servlet/jsp. Container is responsible to dispatch the the control by finding the full path internally either with the context or request. But there is no full dispatch of control, after calling forward with the RequestDispatcher() object control will back to the source servlet. If we want to have full dispatch of control then we must go for sendRedirect(). By calling the forward() method some task is being forward by this method internally. Steps details of which are as under:
Task performed by forward() :
1. First check the response buffer whether data any exist or not. If exist and committed then gives the IllegalStateException and if exist and not committed then erase the existing data.
2. After checking response buffer, preparing path for the requested resource and adds the final path to the request attribute.
3. Then control dispatched to the requested source either a jsp or servlet by invoking the service() method of that servlet.
4. Pass the request and response object of the source servlet to the requested resource service() method as a parameter.
5. Process the code written in the service() method and then ready the response object with the final content from the requested source.
6. Finally returns the response to the RequestDispatcher.
7. RequestDispatcher will commit the response and then control back to the source servlet.
8. Finally that response must be returned to the browser to display the result of the request processing.
Note: Here the response object get committed by the RequestDispatcher object so writing the content further to the reponse in the source servlet will not be reflect.
Here saying dispatching the control to the another servlet/jsp that means we are writing whole content of target servlet the source servlet response object and get displayed in the browser.
Note :
1. Writing any content to the response object before calling the forward will be erased if not committed. IF committed then throw IllegalStateException.
2. Writing content to the response object after calling forward() method will not be written to the response object because it already get committed before by the RequestDsiaptcher.
Why we are saying not completely dispatching the control to the target resource?
As source response object has full content of processed target resource without fully dispatching the control to the target servlet/jsp.
Limitation of forward()
From the above all statements we can conclude that source servlet is not capable of generating any response or cannot add any content to the response object before and after calling the foward(). This is the limitation of the forward().
0 comments:
Post a Comment