3

My application has a JSP, which uses scriplet code to redirect to a page based on some condition.

But what is happening is that, after the redirect code response.redirect(..), the below code is executing. I don't want to execute below code or load the JSP page, I just want to redirect immediately. See the below example and please let me know the solution.

<html>
<body>
<%
    boolean condition = true;
    if(condition)
        response.sendRedirect("http://www.google.co.in");
    System.out.println("I don't want to execute this code, I just want to redirect after above line");
%>
</body>
</html>
Piotr Nowicki
  • 17,914
  • 8
  • 63
  • 82
sampath
  • 155
  • 1
  • 2
  • 7

2 Answers2

4

Return statement can be used as soon as the sendRedirect is done. In this case the code present below that will not be executed.

if(condition){
     response.sendRedirect("http://www.google.co.in");
     return;
}
Thambi
  • 41
  • 2
1

The control is passed to the next URL only after the complete execution of the whole code block ,any statement after sendRedirect would get executed.

If you don't want to print the statement ,you should move that line from there to somewhere like in else block.

<%
    boolean condition = true;
    if(condition)
     response.sendRedirect("http://www.google.co.in");
    else
       System.out.println("I don't want to execute this code, I just want to redirect after         above      line");
%>
Sandeep Pathak
  • 10,567
  • 8
  • 45
  • 57
  • I got the answer, use instead of response.redirect(), that will immediately redirect to the new page – sampath Dec 31 '11 at 14:38
  • 1
    A redirect and a forward are two very different things. Don't use one when the other is needed. You shouldn't redirect in a JSP. This should be done by a servlet or an action of your preferred MVC framework. JSPs should be used to generate markup and nothing else. See http://stackoverflow.com/questions/3177733/how-to-avoid-java-code-in-jsp-files – JB Nizet Dec 31 '11 at 15:28