我在我的 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 错误,如果我在未先登录的情况下尝试查看 protected 内容,页面确实会显示。但是引用的图像丢失了。如果我只是将文件拖到 Web 浏览器中,它会正确显示,所以我认为这是上下文问题。我尝试将 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");
}
}
最佳答案
服务器不会重定向到您的错误页面。它转发给它。因此,如果初始调用的 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
是您应用程序的连接路径)
关于java - 自定义 Tomcat 错误页面不显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14173212/