Author |
Topic: Include vs Redirect |
|
WebSpider member offline |
|
posts: |
147 |
joined: |
06/29/2006 |
from: |
Seattle, WA |
|
|
|
|
|
Include vs Redirect |
Here is the scenario: the user is trying to get page servcie_A.jsp which for somw reason cannot serve the need and thereafter switches to service_B.jsp instead.
user ------> service_A.jsp ------> service_B.jsp
|
|
|
|
|
|
|
WebSpider member offline |
|
posts: |
147 |
joined: |
06/29/2006 |
from: |
Seattle, WA |
|
|
|
|
|
Solution with INCLUDE |
On the page service_A.jsp:
if(failed){
request.setAttribute("request_attr", "request_attr_value");
session.setAttribute("session_attr", "session_attr_value");
request.getRequestDispatcher("service_B.jsp").include(request, response);
}else{
...
}
|
|
|
|
|
|
|
WebSpider member offline |
|
posts: |
147 |
joined: |
06/29/2006 |
from: |
Seattle, WA |
|
|
|
|
|
Solution with REDIRECT |
On the page service_A.jsp:
if(failed){
request.setAttribute("request_attr", "request_attr_value");
session.setAttribute("session_attr", "session_attr_value");
response.sendRedirect("service_B.jsp");
}else{
...
}
|
|
|
|
|
|
|
WebSpider member offline |
|
posts: |
147 |
joined: |
06/29/2006 |
from: |
Seattle, WA |
|
|
|
|
|
Observations |
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.
|
|
|
|
|
|
|
WebSpider member offline |
|
posts: |
147 |
joined: |
06/29/2006 |
from: |
Seattle, WA |
|
|
|
|
|
RequestDispatcher.include vs. RequestDispatcher.forward |
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. |
|
|
|
|
|
|
|