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

查看:355
本文介绍了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.

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

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中声明一个<error-page>,您可以在其中指定应显示在特定

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.Error.这样,您可以为任何类型的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" %>,则可以访问抛出的

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教程.

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

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