gpt4 book ai didi

jsp - 服务器如何优先使用哪种类型的 web.xml 错误页面?

转载 作者:行者123 更新时间:2023-11-28 21:45:29 25 4
gpt4 key购买 nike

我有两个错误页面; 1 用于 SpecificExceptionA,另一个用于 Throwable。

<error-page>
<exception-type>org.SpecificExceptionA</exception-type>
<location>/WEB-INF/views/error/timedout.jsp</location>
</error-page>

<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/WEB-INF/views/error/error.jsp</location>
</error-page>

如果我在我的 web.xml 中定义了这两个,一切都会转到/error/error.jsp。

如果我只定义了特定的异常,它会转到正确的页面;但其他错误转到tomcat默认(404除外)

有没有更好的方法来指定特定的异常处理程序?我正在使用 spring 3.0。

最佳答案

这不是 Tomcat 特有的。这是特定于 Servlet API 的。 Servlet API specification 2.5 的第 9.9.2 章中指定了如何确定错误页面。 .以下是相关摘录:

SRV.9.9.2 Error Pages

If no error-page declaration containing an exception-type fits using the class-hierarchy match, and the exception thrown is a ServletException or subclass thereof, the container extracts the wrapped exception, as defined by the ServletException.getRootCause method. A second pass is made over the error page declarations, again attempting the match against the error page declarations, but using the wrapped exception instead.

因此,您的 SpecificExceptionA 可能包含在 ServletException 中因此 java.lang.Throwable 是第一遍中最接近的匹配项。当您删除此条目时,将使用包装的异常进行第二次传递,因此您的 SpecificExceptionA 得到匹配。

定义一般 HTTP 500 错误页面的正确方法是将其映射到 error-code 而不是 exception-type:

<error-page>
<exception-type>org.SpecificExceptionA</exception-type>
<location>/WEB-INF/views/error/timedout.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/WEB-INF/views/error/error.jsp</location>
</error-page>

如果由于某些不明确的原因这不是一个选项,解决此问题的方法之一是创建一个 Filter 来监听 url-pattern >/* 并基本上执行以下操作:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
try {
chain.doFilter(request, response);
} catch (ServletException e) {
Throwable rootCause = e.getRootCause();
if (rootCause instanceof SpecificExceptionA) {
throw (SpecificExceptionA) rootCause;
} else {
throw e;
}
}
}

它只需要从 RuntimeException 扩展就可以让它工作。

关于jsp - 服务器如何优先使用哪种类型的 web.xml 错误页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5299169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com