Unable to redirect with response.sendRedirect

I google and google for hours on how to do redirection in jsp or servlets. However, when I try to apply it, it does not work.

The code I have on the jsp page is:

<% 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 at any time articleId is not a number, if goes inside, however, when it reaches response.sendRedirect, it does not actually redirect.

Did I miss something very fundamental in this case?

Thanks in advance.

+6
java regex jsp servlets jstl
source share
2 answers

You should return after the redirect:

 response.sendRedirect("index.jsp"); return; 
+22
source share

Is there any content before this script? If so, the redirect will not work.

In addition, a common practice is to have this logic inside a servlet or other class that serves as a controller and leave the JSP only processing HTML rendering. It can also solve your problem. For example, see here .

+1
source share

All Articles