Subject: RequestDispatcher.include vs. RequestDispatcher.forward
Author: WebSpider
In response to: Observations
Posted on: 09/17/2012 02:31:08 PM
if(failed){
request.setAttribute("request_attr", "request_attr_value");
session.setAttribute("session_attr", "session_attr_value");
request.getRequestDispatcher("service_B.jsp").include(request, response);
...
request.getRequestDispatcher("service_C.jsp").include(request, response);
}else{
...
}
or
if(failed){
request.setAttribute("request_attr", "request_attr_value");
session.setAttribute("session_attr", "session_attr_value");
request.getRequestDispatcher("service_B.jsp").forward(request, response);
return;
}else{
...
}
The key difference between the two is the fact that the
include method leaves the output stream open, whereas the
forward method will close the output stream after it has been invoked.
With
include, you can continue processing any stuff which can be put into output stream or even inject another jsp page (
service_C.jsp); With
forward, however, you had better stop (
return;) unless the remaining task is just background stuff, otherwise,
IllegalStateException would be thrown.
>
> On 09/30/2010 03:23:07 PM
WebSpider wrote:
INCLUDE:
user ----> service_A.jsp ---> service_B.jsp
<-----------------------
1) one traffic;
2)url remains unchanged;
3)request's attribute passed as expected.
4)session's attribute passed with no surprise.
REDIRECT:
user ----> service_A.jsp service_B.jsp
<----
user -----------------------> service_B.jsp
<-----------------------
1) two traffic: one returns with 302 Moved Temorarily, and the other returns with service_B.jsp;
2)url changed as expected;
3)request's attribute not passed as expected.
4)session's attribute passed with no surprise.
References: