Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Page is still executed even after response.sendRedirect()

 
Susan Smith
Ranch Hand
Posts: 224
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the beginning of a JSP page, I checked for a variable called "sessionLogin" everytime a user click a submit button in a form. And if this variable is empty or NULL then I redirect to another page called "invalidLogin.jsp".

I have checked and the redirection is working ok. But the second if statement below keeps getting executed even though the page is redirected.
I don't know why. Could someone please advise? I'm probably missing something trivial here.

 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The sendRedirect method does not halt the execution of your method.
You should either branch your code in such a way that the call to sendRedirect is the last statement in your method or explicitly call return; after calling sendRedirect.
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The same applies to RequestDispatcher.forward.
 
Susan Smith
Ranch Hand
Posts: 224
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But I've done a test below and the page is redirected to test2.jsp immediately and the alert statement in test1.jsp is not being executed. Why is that?

 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because the sendRedirect method was called.

Remember, these are just Java methods calling one another.
The rules don't change just because they're servlets (or servlets generated by JSPs).

sendRedirect gets called, as soon as it's done, the code under is executed.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64633
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The alert() is JavaScript and has nothing to do with your JSP. It is not executed at the same time as the JSP which executes on the server.

Perhaps this article would be helpful.
 
Susan Smith
Ranch Hand
Posts: 224
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the help.

Let me read the article.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic