简体   繁体   中英

Cannot redirect with the response.sendRedirect

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.

You should return after redirecting:

response.sendRedirect("index.jsp");
return;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM