1

我在 web.xml 文件中配置了一个自定义错误页面,但页面中引用的图像显示为断开的链接。

自定义错误页面只是一个简单的 html 页面:

<!DOCTYPE html>
<html><head>
  <meta charset="UTF-8"><title>401 Error</title></head>
<body>
    <p style="font-size: 200%; text-align: center">HTTP Error 401: Not authorized to view sensitive data.<br/>
    <img src="NoAccessImage.png" alt="401Error"><br/>
    You must log in before viewing the requested page.</p>
</body></html>

此页面与其引用的图像文件一起存储在错误文件夹中。身份验证过滤器用于抛出 401 错误,如果我在未先登录的情况下尝试查看受保护的内容,则该页面会显示。但引用的图像丢失了。如果我只是将文件拖到网络浏览器中,它会正确显示,所以我认为这是一个上下文问题。我尝试将 img src 标签更改为"/error/NoAccessImage.png"没有结果。

相关的 AuthenticationFilter 代码如下:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {    
    try {
        boolean authorized = false;
        HttpServletRequest r = (HttpServletRequest) request;
        HttpSession session = ((HttpServletRequest)request).getSession(false); 
        String uri = r.getRequestURI();
        if(uri.indexOf("/Login")>0) {
            chain.doFilter(request, response);
            return;               
        }
        if (session != null) {
            String school = (String) session.getAttribute("school");
            if(school != null && school.length()>0 ) {
                authorized = (school.equals(getURISchool(uri)));
            }
        }
        if (authorized) {
            chain.doFilter(request, response);
            return;
        } else {
            ((HttpServletResponse) response).sendError(401, "You must log in to view the schedule.");
        }
    } catch (IOException io) {
        System.out.println("IOException raised in AuthenticationFilter");
    } 
}
4

2 回答 2

2

服务器不会重定向到您的错误页面。它转发给它。因此,如果初始调用的 URL 是http://localhost/myApp/foo/bar/baz/SomeAction,由于您使用了图像的相对路径,浏览器将在http://localhost/myApp/foo/bar/baz/NoAccessImage.png. 因此,您应该使用绝对路径来引用图像(以及所有图像、资源和链接)。

由于每个应用程序都有一个上下文路径,因此您必须将上下文路径添加到 URL。这就是 JSTL<c:url>标签的作用:

<img src="<c:url value='/error/NoAccessImage.png'/>" alt="401Error"/>

这将被翻译成

<img src="/myApp/error/NoAccessImage.png" alt="401Error"/>

myApp作为您的应用程序的连接路径)

于 2013-01-05T15:38:07.540 回答
1

过滤器对于 的请求不得处于活动状态/error/*。据我了解,从您提供的浏览器向 发送请求的信息中/error/NoAccessImage.png,该请求通过过滤器运行,服务器以 401 而不是图像响应。

在您选择的浏览器中使用开发控制台(通常使用 F12 激活)查看请求/响应及其各自的 HTTP 状态代码。

此外,如果您的应用程序使用上下文根而不是/ie is itserver:port/foo/index.servletserver:port/index.servlet. 如果是前者,则图像的路径必须是/foo/error/NoAccessImage.png.

于 2013-01-05T15:36:55.937 回答