This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
I've just read a book that describes a little about RequestDispatcher. It is said that both ServletContext and ServletRequest has method getRequestDispatcher() that returns RequestDispatcher, but it doesn't explains any specific behaviour about this (Request Dispatcher scope or life cycle or something like that). Actually, what is the difference between them?
Another question. It is said that RequestDispatcher has method forward() and include(). What is the difference between them? Both has same functionality, isn't it? After all, one of them can be used to forwarding request to another servlet that designed for specific task after partially processed in current servlet (who calls forward or include). After all, why should we need forward() or include()? Why dont just servlet X calls the doXXX() method of servlet Y instead of call forward() or include()? After all, the doXXX() is always public...
What is the difference between them? Both has same functionality, isn't it?
forward() tells RequestDispatcher to clear any response already written and have another servlet process the entire response for the current request. Once the destination servlet is done the response is complete. Control will not return to the current servlet.
include() tells the RequestDispatcher to run another servlet, write any output to the response and return to the current servlet.
forward() is a one-way trip to another servlet. include() will return control to the current servlet.
Why dont just servlet X calls the doXXX() method of servlet Y instead of call forward() or include()?
There are many reasons you don't want to use the doXXX methods directly. Here are a few:
By calling servlet methods directly you are making assumptions about which servlet should process the request. By using include() or forward() you let the servlet container map the target url to a servlet.
The servlet container manages the lifecycle of servlets. To call the doXXX methods directly you would have to instantiate your own instance of the servlet. That's not a best practice.
If you call doGet() and doPost() directly, you avoid the normal processing that precedes running a servlet such as filters, security, etc.
Finally, calling doGet() and doPost() directly makes an assumption that the servlet is an HTTP servlet. [ October 31, 2006: Message edited by: Scott Johnson ]