142

当用户遇到特定错误(例如代码为 404 的错误)时, 我使用web.xml<error-page>中的元素来指定友好的错误页面:

<error-page>
        <error-code>404</error-code>
        <location>/Error404.html</location>
</error-page>

但是,我希望如果用户不符合 中指定的任何错误代码<error-page>,他或她应该会看到默认错误页面。如何使用web.xml中的元素来做到这一点?

4

3 回答 3

246

在 Servlet 3.0 或更高版本上,您可以指定

<web-app ...>
    <error-page>
        <location>/general-error.html</location>
    </error-page>
</web-app>

但是由于您仍在使用 Servlet 2.5,因此除了单独指定每个常见的 HTTP 错误之外别无他法。您需要确定最终用户可能面临哪些 HTTP 错误。在准系统 web 应用程序上,例如使用 HTTP 身份验证、禁用目录列表、使用可能引发未处理异常或未实现所有方法的自定义 servlet 和代码,然后您希望将其设置为 HTTP 错误 401 , 403, 500 和 503。

<error-page>
    <!-- Missing login -->
    <error-code>401</error-code>
    <location>/general-error.html</location>
</error-page>
<error-page>
    <!-- Forbidden directory listing -->
    <error-code>403</error-code>
    <location>/general-error.html</location>
</error-page>
<error-page>
    <!-- Missing resource -->
    <error-code>404</error-code>
    <location>/Error404.html</location>
</error-page>
<error-page>
    <!-- Uncaught exception -->
    <error-code>500</error-code>
    <location>/general-error.html</location>
</error-page>
<error-page>
    <!-- Unsupported servlet method -->
    <error-code>503</error-code>
    <location>/general-error.html</location>
</error-page>

这应该涵盖最常见的那些。

于 2011-08-15T15:01:10.320 回答
25

You can also do something like that:

<error-page>
    <error-code>403</error-code>
    <location>/403.html</location>
</error-page>

<error-page>
    <location>/error.html</location>
</error-page>

For error code 403 it will return the page 403.html, and for any other error code it will return the page error.html.

于 2015-07-08T06:27:28.893 回答
10

您还可以<error-page>使用 指定异常<exception-type>,例如:

<error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/errorpages/exception.html</location>
</error-page>

或使用以下方法映射错误代码<error-code>

<error-page>
    <error-code>404</error-code>
    <location>/errorpages/404error.html</location>
</error-page>
于 2018-02-19T08:26:37.270 回答