Java Servlet过滤器重定向问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2190733/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 19:56:48  来源:igfitidea点击:

Java Servlet Filter redirect problem

javaservletsservlet-filters

提问by Stian

I'm having a problem with my authentication filter. When the filter redirects to the login page, no images gets displayed in the login JSP. However, if I go to the login page manually after I'm logged in, the images are displayed.

我的身份验证过滤器有问题。当过滤器重定向到登录页面时,登录 JSP 中不会显示任何图像。但是,如果我在登录后手动转到登录页面,则会显示图像。

I don't understand why this is happening! I appreciate any help. :-)

我不明白为什么会这样!我很感激任何帮助。:-)

AuthFilter:

身份验证过滤器:

if (authorized == null && path.indexOf("Auth") == -1 && path.indexOf("Login") == -1 ) {
        httpResponse.sendRedirect("Login");  
        return;  
} else {  
        chain.doFilter(request, response);  
}

Login servlet:

登录小服务程序:

// Just using a servlet in case I want more data sent to the jsp
Dispatcher.dispatch("views/login.jsp", request, response);

login.jsp:

登录.jsp:

<img src="images/logo.png" />

The jsp is otherwise "normal", all required HTML tags are present. The "images" folder is in the default "web" folder of the project, alongside all the other jsp's and javascripts.

否则,jsp 是“正常的”,所有必需的 HTML 标签都存在。“images”文件夹位于项目的默认“web”文件夹中,与所有其他jsp和javascripts一起。

Thanks in advance for any help. :)
- Stian

在此先感谢您的帮助。:)
- 斯蒂安

回答by Bozho

It's because of the relative paths.

这是因为相对路径。

  • your Loginis in the root of the context
  • your images probably are /views/images/
  • when you forward, the browser knows only the requested URL.
  • Login在上下文的根
  • 你的图片可能是 /views/images/
  • 当您转发时,浏览器只知道请求的 URL。

So when you forward, the images are sought at /images(because they are relative to the current address) instead of /views/images/

因此,当您转发时,会查找图像/images(因为它们与当前地址相关)而不是/views/images/

How to resolve it. Two options:

如何解决。两种选择:

  • don't forward from your servlet; redirect instead
  • don't redirect to the servlet from the filter; redirect to the login page directly
  • 不要从您的 servlet 转发;改为重定向
  • 不要从过滤器重定向到 servlet;直接跳转到登录页面

Update: Make sure the images are NOT affected by the filter. two options:

更新:确保图像不受过滤器的影响。两个选项:

  • they should not be matched by the filter pattern
  • redirection should not happen for .png, .jpeg, .css, etc. in the filter. check this with request.getRequestURI()
  • 它们不应与过滤器模式匹配
  • 过滤器中的 .png、.jpeg、.css 等不应发生重定向。检查这个request.getRequestURI()

回答by Thilo

Could it be that your filter is also applied to image requests and redirects the request for logo.pngto login.jsp?

难道您的过滤器也适用于图像请求并将请求重定向logo.pnglogin.jsp

If so, you could adjust the filter-mappingin web.xml.

如果是这样,您可以调整filter-mappingin web.xml