Java Servlet 过滤器重定向,url 未更改
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18526672/
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
Servlet filter redirect, url not changed
提问by Mitja Rogl
I'm having a problem with my authentication filter. When the filter redirects to the login page, all the previous page(main page) is displayed in the login page. If I go to the login page manually it works fine.
我的身份验证过滤器有问题。当过滤器重定向到登录页面时,所有以前的页面(主页面)都显示在登录页面中。如果我手动进入登录页面,它工作正常。
Here is my filter:
这是我的过滤器:
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
HttpSession session = req.getSession(false);
String loginURL = req.getContextPath() + SiteMap.LOGIN_CONTROLLER;
boolean sessionCreated = session != null && !session.isNew();
if (sessionCreated)
{
chain.doFilter(request, response);
}
else
{
res.sendRedirect(loginURL);
}
I also noted that when filter redirects to the login page the URL in browser bar stays the same. The main problem is that I get content from other page in the login page. Don't know where is the problem.
我还注意到,当过滤器重定向到登录页面时,浏览器栏中的 URL 保持不变。主要问题是我从登录页面的其他页面获取内容。不知道问题出在哪里。
回答by sameer_mishra
what is the value of loginURL that you are passing . Send a relative path.
您传递的 loginURL 的值是多少。发送相对路径。
回答by Siva
Changing the URl in browser did not depends on filter but it depends on how you are calling the page/servlet. You can call your servlet/jsp in two ways
在浏览器中更改 URl 并不取决于过滤器,而是取决于您如何调用页面/servlet。您可以通过两种方式调用您的 servlet/jsp
RequestDispatcher: Transfers the control to other under the same request (Same URL)
Send Redirect: Initiates a new request (New Url)
Note : All that filter will do is a validation for the request
RequestDispatcher:将控制权转移给同一请求下的其他人(相同 URL)
发送重定向:发起新请求(新 URL)
注意:过滤器所做的只是对请求进行验证
回答by Kemin Zhou
I was having the exact same problem. The real problem is that I and you both forgot to add the following line:
我遇到了完全相同的问题。真正的问题是我和你们都忘记添加以下行:
response.setContentType("text/html");
After adding this line my redirect works fine. Before this my servlet will stay on the same page with a blank page (because nothing has been written to the response oputput stream).
添加此行后,我的重定向工作正常。在此之前,我的 servlet 将保留在同一页面上,并带有一个空白页面(因为没有将任何内容写入响应输出流)。
Hope this may help others who is having this problem. It took me some painful minutes before test this possibility.
希望这可以帮助遇到此问题的其他人。在测试这种可能性之前,我花了一些痛苦的时间。