Cannot redirect with the response.sendRedirect
Asked Answered
R

2

6

I googled and googled for hours on how to make a redirect in jsp or servlets. However when i try to apply it, it doesn't work.

Code that i have inside jsp page:

<%
    String articleId = request.getParameter("article_id").toString();
    if(!articleId.matches("^[0-9]+$"))
    {
       response.sendRedirect("index.jsp");
    }
%>

I know from debugging that regexp works and if any time, articleId is not number, the if goes inside, however when it reaches response.sendRedirect it doesn't actually makes redirect.

Do I miss something very fundamental in this case ?

Thanks in advance.

Richardo answered 7/6, 2009 at 3:12 Comment(0)
A
22

You should return after redirecting:

response.sendRedirect("index.jsp");
return;
Anthropophagite answered 7/6, 2009 at 4:10 Comment(2)
It's worth considering the "why" of this. The sendRedirect() adds a header to the HTTP response, and that's it. If you then proceed to write some content to the response, then the browser may consider the redirect header to be superfluous, and ignore it. It's always worth considering the order in which you call methods on the response object, it can often lead to odd failure modes without an obvious reason. The Servlet API is pretty explicit at describing these potential problems.Surveyor
I also have the same problem, I tried this solution but not woking there, please helpCohosh
D
1

Is there content before this scriptlet? If so, the redirect wouldn't work.

Also, the common practice is to have such logic inside a servlet or other class serving as controller, and leaving the JSP to only handle the rendering of the HTML. It may also solve your problem. For example, see here

Doggish answered 7/6, 2009 at 3:54 Comment(1)
I also have the same problem, I tried this solution but not woking there, please helpCohosh

© 2022 - 2024 — McMap. All rights reserved.