Java 无法使用 response.sendRedirect 重定向
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/961124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot redirect with the response.sendRedirect
提问by Dmitris
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.
我在 google 上搜索了几个小时,了解如何在 jsp 或 servlet 中进行重定向。但是,当我尝试应用它时,它不起作用。
Code that i have inside jsp page:
我在jsp页面中的代码:
<%
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.
我从调试中知道 regexp 有效,并且如果任何时候,articleId 不是数字,则if
进入内部,但是当它到达 response.sendRedirect 时,它实际上并没有进行重定向。
Do I miss something very fundamental in this case ?
在这种情况下,我是否错过了一些非常基本的东西?
Thanks in advance.
提前致谢。
采纳答案by objects
You should return
after redirecting:
您应该return
在重定向后:
response.sendRedirect("index.jsp");
return;
回答by David Rabinowitz
Is there content before this scriptlet? If so, the redirect wouldn't work.
这个scriptlet之前有内容吗?如果是这样,重定向将不起作用。
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
此外,通常的做法是在 servlet 或其他用作控制器的类中拥有这样的逻辑,而让 JSP 只处理 HTML 的呈现。它也可以解决您的问题。例如,请参见此处