Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

sendRedirect(Url)

 
Salima Lalani
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All ,
I came across following example from Hanumant's book
public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException,IOException
{

PrintWriter pw = res.getWriter();
pw.println("<html><body>HelloWorld</body></html>");
pw.flush();
res.sendRedirect("http://www.cnn.com");

}
The explanation of example says that since the response header are always sent to the browser, so this method will throw IllegalStateException.
When i run this code, it worked fine, except it didn't redirect to the url. If i comment the flush() , then it redirects me to cnn.com.
I don't understand what is meant by committed response. When the above example will throw exception.
Will appreciate your kind help.
 
Mark Howard
Ranch Hand
Posts: 285
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Salima
The response is being committed when pw.flush() executes. ie A res.isCommitted() immediately afterwards will return true.
Also, the res.sendRedirect("...") does throw an IllegalStateException. You can test this in a try...catch clause.
So.... the Servlet side of things is working as expected. I'm guessing that the browser doesn't care about the exception and accepts the state of the response at the time it was committed. You would probably need to catch the exception and use sendError() to display a meaningful error on the browser.
Hope this helps
Mark.
 
Salima Lalani
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Mark,
I tried working as you said. But it is not throwing an exception. Pls post your code so that i can understand.
Thanks a lot!!!
Salima
 
Mark Howard
Ranch Hand
Posts: 285
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Salima
After pw.flush(), code the following try...catch:

Your output should include: "An IllegalStateException occurred"
Mark.
 
Salima Lalani
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mark,
I got it.
Thanks
Salima
 
vn us
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To continue on this question
Can i set a Header say "name" as the header name and value is "MYNAME" in the response object and call the response.sendRedirect( url ) and Can i access the same header ( "name" ) in the redirected url?
Thanks,
AVNUS
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic