• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

response.sendRedirect vs. request.getRequestDispatcher

 
Jason Stortz
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay, I'm using Tomcat 4.0.4. I'm having a hard time deciding when to use response.sendRedirect() and when to use request.getRequestDispatcher(someURL).forward(request, response).
We used to use response.sendRedirect all over the place, but that started failing once we moved from iPlanet 4.1 to Tomcat. I need to redirect the user OFF our site to another site though, so the forward method of RequestDispatcher doesn't work since it has to be a relative path.
Anyone got any hard and fast rules here? response.sendRedirect only seems to work some of the time, and I cannot tell why.
Any advice would be awesome.
Thanks,
Jason
 
raj sekar
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jason,
We should keep in mind a couple of important points about the sendRedirect()
method.
* We cannot call this method if the response is committed,
that is, if the response header has already been sent to the browser.
If we do, the method will throw a java.lang.IllegalStateException.

For ex:
public void doGet(HttpServletReqeust req, HttpServletResponse res)
{
PrintWriter pw = res.getPrintWriter();
pw.println("<html><body> Hello World </body></html>");
pw.flush(); // send the response
res.sendRedirect("http://www.javaranch.com"); // Tries to Redirect
}

Thanks,
Raj
 
Paul McKenna
Ugly Redneck
Ranch Hand
Posts: 1006
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another point worthy of keeping in mind is that if you use the response.sendRedirect method your request parameters will be lost. However, the requestDispatcher.forward retains these parameters and makes them available to the called servlet/jsp.
SR
 
ticco scott
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is in reference to your comments on sendRedirect()---
* We cannot call this method if the response is committed,
that is, if the response header has already been sent to the browser.
If we do, the method will throw a java.lang.IllegalStateException.

For ex:
public void doGet(HttpServletReqeust req, HttpServletResponse res)
{
PrintWriter pw = res.getPrintWriter();
pw.println("<html><body> Hello World </body></html>");
pw.flush(); // send the response
res.sendRedirect("http://www.javaranch.com"); // Tries to Redirect
}


We are running into similar issue with requestDispathcer.forward() too (i.e. the output was partially written out to the buffer before making the call to forward )
I was under the impression that with server side forward this should not happen ???

What are your comments on this??

Plz respond.


-Thanx,
ticco
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic