问题描述
我正在使用 Tomcat.我在 web.xml
中定义了一些 并将
404
错误映射到页面 /error/error.jsp代码>.我需要检测资源是否存在,如果资源不可用,将响应状态设置为 404.
I am using Tomcat. I defined some <error-page>
in web.xml
and mapped 404
error to page /error/error.jsp
. I need to detect if the resource exist and set the response status to 404 if the resource is not available.
response.setStatus(404);
但是Tomcat并没有重定向到我定义的404页面,所以我的问题是,是否有任何API可以获取web.xml
中定义的页面位置?我不想自己解析web.xml
.
But Tomcat does not redirect to the 404 page I defined, so my question is, is there any API to get the page location defined in web.xml
? I don't want to parse the web.xml
by myself.
推荐答案
只需使用 HttpServletResponse#sendError()
带有 状态代码.例如
File resource = new File(path, name);
if (!resource.exists()) {
response.sendError(HttpServletResponse.SC_NOT_FOUND); // Sends 404.
return;
}
servletcontainer 将显示合适的错误页面.
The servletcontainer will then display the suitable errorpage.
注意:return
语句不是用来装饰的.这将避免同一方法块中的剩余代码将继续运行并可能在应用服务器日志中产生 IllegalStateException
!初学者通常认为像 sendRedirect()
、forward()
、sendError()
等方法在调用时会以某种方式自动退出方法块.因此这不是真的;)
Note: the return
statement isn't there for decoration. It will avoid that the remant of the code in the same method block will continue to run and might produce IllegalStateException
s in the appserver logs! Starters namely often think that methods like sendRedirect()
, forward()
, sendError()
, etc somehow automagically exits the method block when invoked. This is thus not true ;)
这篇关于如何将 servlet 响应发送到 web.xml 配置的错误页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!