• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why the prm continue executing after I put "response.sendRedirect()" ?

 
Steve Yu
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a central servlet including --
doGet(HttpServletRequest request, HttpServletResponse response) {
MyAction action = new MyAction();
action.doSomething(request, response);
}
And in the "MyAction" class it looks like --
class MyAction {
public void doSomething(HttpServletRequest request, HttpServletResponse response) {
doSecond(response, String abc);
}
public void doSecond(HttpServletResponse res, String s) {
if(s.equals("abc")) {
res.sendRedirect("some URL");
}
doThird();
}
}

My understanding is -- if the "if" condition in doANother is satisfied, then the prm stop be stopped after the HttpResponse directs to "some URL", but the case is -- the page is directed to "some URL" but the "doThird" is still executed, which is not what I want. Is that supposed to be like that ? If yes, how can I let the pgm stop immediately ?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When sendRedirect returns, execution of your first servlet continues. Most often, a call to sendRedirect() is followed by a "return" so that there's no more output from the originating servlet -- i.e.

Of course, with your methods calling methods calling other methods, you'll need to make sure that after the redirect, all the nested method calls of your servlet return immediately.
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could throw a private runtime exception after sendRedirect, and catch it in doGet, though this seems a bit baroque.
 
Steve Yu
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, how about adding a "System.exit(0)" after that "sendRedirect()" ? Is it safe to do that ?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, that call would fail with a SecurityException -- any servlet container worth its salt will stop servlets from calling this method. The exception would propagate up, and you'd end up with a server error. The page would already be served, though, so I'm not sure if the client would see it or not.
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tomcat 4.1.24 happily executes a servlet that contains a System.exit(0); call. Which shuts down the whole server!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic