当 servlet 抛出运行时异常时,如何在浏览器中显示用户友好的错误页面? [英] How to show user-friendly error page in browser when runtime exception is thrown by servlet?

查看:22
本文介绍了当 servlet 抛出运行时异常时,如何在浏览器中显示用户友好的错误页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 JSF 开发 Web 应用程序.我尽可能地对其进行了测试,但有时会抛出运行时异常.

I'm developing web-application with JSF. I tested it as I was able to but from time to time runtime exceptions are thrown.

那么,如何在每次抛出异常时将用户重定向到特殊的错误页面(而不是显示 500 Error 和完整的 tomcat 日志)?

So, how to redirect user to special error page every time an exception is thrown (instead of displaying 500 Error with full tomcat logs)?

推荐答案

只需在 web.xml 中声明一个 即可指定页面这应该显示在某个 Throwable(或其任何子类)或 HTTP 状态代码.例如

Just declare an <error-page> in web.xml wherein you can specify the page which should be displayed on a certain Throwable (or any of its subclasses) or a HTTP status code. E.g.

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

将在 java.lang.Exception 的任何子类上显示错误页面,但不是 java.lang.Throwablejava.lang.错误.通过这种方式,您可以为任何类型的 Throwable 拥有自己的错误页面.例如.java.sql.SQLExceptionjava.io.IOException 等.

which will display the error page on any subclass of the java.lang.Exception, but thus not java.lang.Throwable or java.lang.Error. This way you can have your own error page for any kind of Throwable. E.g. java.sql.SQLException, java.io.IOException and so on.

或者,

<error-page>
    <error-code>500</error-code>
    <location>/error.jsp</location>
</error-page>

这将显示 HTTP 500 错误的错误页面,但您也可以为 404(未找到页面)、403(禁止)等指定另一个页面.

which will display the error page on a HTTP 500 error, but you can also specify another ones for 404 (Page Not Found), 403 (Forbidden), etcetera.

如果您在 error.jsp 顶部声明 <%@page isErrorPage="true" %>,则您可以访问抛出的 Exception(因此也它的所有吸气剂)由 EL 中的 ${exception} 提供.

If you declare <%@page isErrorPage="true" %> in top of error.jsp, then you have access to the thrown Exception (and thus also all of its getters) by ${exception} in EL.

<p>Message: ${exception.message}</p>

另请参阅有关该主题的 Java EE 5 教程.

Also see the Java EE 5 tutorial on the subject.

这篇关于当 servlet 抛出运行时异常时,如何在浏览器中显示用户友好的错误页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆