views:

821

answers:

2

Hello everybody,

I gooogled 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 debugin that regexp works and 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.

+1  A: 

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

David Rabinowitz
+2  A: 

you should return after redirecting

       response.sendRedirect("index.jsp");
       return;
objects
Thats was it. Adding return is worked. Thank you.
Dmitris
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.
skaffman