在servlet引发运行时异常时,如何在浏览器中显示用户友好的错误页面?(How to show user

系统教程 行业动态 更新时间:2024-06-14 17:01:34
在servlet引发运行时异常时,如何在浏览器中显示用户友好的错误页面?(How to show user-friendly error page in browser when runtime exception is thrown by servlet?)

我正在使用JSF开发Web应用程序。 我测试了它,因为我能够但不时地运行时异常被抛出。

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

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

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> ,其中您可以指定应该在某个Throwable (或其任何子类)上显示的页面或HTTP状态代码 。 例如

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

这将在java.lang.Exception任何子类上显示错误页面,但不会显示java.lang.Throwable或java.lang.Error 。 这样你可以有任何类型的Throwable自己的错误页面。 例如java.sql.SQLException , java.io.IOException等。

要么,

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

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

如果你在error.jsp顶部声明了<%@page isErrorPage="true" %> ,那么你可以访问EL中抛出的Exception (因此也是所有的getter) ${exception} 。

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

另请参阅有关此主题的Java EE 5教程 。

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>
 

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.

Or,

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

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.

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>
 

Also see the Java EE 5 tutorial on the subject.

更多推荐

本文发布于:2023-04-20 18:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/74c97fd7a5babe309c7020f169e1f853.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:友好   器中   异常   错误   页面

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!