JSF 1.x 通用异常处理

发布于 2024-07-12 19:50:14 字数 91 浏览 6 评论 0原文

如果我的业务层中出现异常(例如 JDBC 连接 bean 中的 SQL 异常),我如何使用自定义消息将其传播到全局 error.jsp 页面?

If I have an exception in my business layer (e.g. a SQL exception in my JDBC connection bean), how can I propagate it with a custom message to a global error.jsp page?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

暮年慕年 2024-07-19 19:50:14

JSF 1.x 不提供这种类型的任何隐式错误处理,尽管您可以使用导航规则(假设表单帖子)重定向到错误页面...

<navigation-case>
<description>
Handle a generic error outcome that might be returned
by any application Action.
</description>
<display-name>Generic Error Outcome</display-name>
<from-outcome>loginRequired</from-outcome>
<to-view-id>/must-login-first.jsp</to-view-id>
</navigation-case>

...或使用重定向...

FacesContext context = FacesContext.getCurrentInstance();
ExternalContext extContext = context.getExternalContext();
String url = extContext.encodeActionURL(extContext
        .getRequestContextPath()
        + "/messages.faces");
extContext.redirect(url);

我建议查看有关更多详细信息,请参阅 JSF 规范

错误消息可以根据需要放置在请求范围/会话范围/url 参数上。


假设有一个 Servlet 容器,您可以使用通常的 web.xml 。 xml错误页面配置

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

在支持 bean 中,您可以在 运行时异常

一些 JSF 实现/框架会捕获这些错误(Apache MyFaces/Facelets),因此您必须配置它们不

JSF 1.x doesn't provide any implicit error handling of this type, though you can redirect to an error page using navigation rules (assuming a form post)...

<navigation-case>
<description>
Handle a generic error outcome that might be returned
by any application Action.
</description>
<display-name>Generic Error Outcome</display-name>
<from-outcome>loginRequired</from-outcome>
<to-view-id>/must-login-first.jsp</to-view-id>
</navigation-case>

...or using a redirect...

FacesContext context = FacesContext.getCurrentInstance();
ExternalContext extContext = context.getExternalContext();
String url = extContext.encodeActionURL(extContext
        .getRequestContextPath()
        + "/messages.faces");
extContext.redirect(url);

I recommend looking at the JSF specification for more details.

Error messages can be placed on the request scope/session scope/url parameters, as you like.


Assuming a Servlet container, you can use the usual web.xml error page configuration.

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

In your backing bean, you can wrap and throw your checked exceptions in RuntimeExceptions.

Some JSF implementations/frameworks will catch these errors (Apache MyFaces/Facelets), so you'll have to configure them not to.

九八野马 2024-07-19 19:50:14

在 JSF 中向用户显示错误消息的一般方法是使用 FacesMessage:

在 Java 端:

...
if (errorOccurred) {
    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("An error occurred blabla..."));
}

在 JSF(JSP 或 XHTML)页面中,只需使用 页面中的组件以显示错误。

The general way to display error message to the user in JSF is to use FacesMessage:

On Java side:

...
if (errorOccurred) {
    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("An error occurred blabla..."));
}

and in the JSF (JSP or XHTML) page, simply use the <h:messages/> component in your page in order to display the error.

热情消退 2024-07-19 19:50:14

您可以放入

<%@ page errorPage="error.jsp" %>

jour jsp/jsf 页面。 在 error.jsp 中,jou 将具有:

<%@ page isErrorPage="true" %>

isErrorPage="true" 将为您的页面提供另一个隐式对象:异常(与您在 jsp 页面上已有请求和响应的方式相同)。 然后您可以从异常中提取消息。

其他详细信息

You can put

<%@ page errorPage="error.jsp" %>

in jour jsp/jsf page. In error.jsp, jou would have:

<%@ page isErrorPage="true" %>

isErrorPage="true" will give your page another implicit object: exception (the same way you already have request and response on jsp page). You can then extract message from exception.

Additional details

怼怹恏 2024-07-19 19:50:14

我在站点页面中创建了一个错误页面,并放置了错误的堆栈跟踪
此代码首先将其放在 web.xml 中,

<error-page>
                <error-code>500</error-code>
                <location>/errorpage.jsf</location>
</error-page>

而 jsf 页面有此代码。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      >
<h:head>
    <h:outputStylesheet name="EstilosOV.css" library="css" />
    <!-- <h:outputScript name="sincontext.js" library="scripts"/> -->

</h:head>
<h:body >
<table width="338" border="0" align="center" bordercolor="#FFFFFF">

    <tr bgcolor="#1D2F68">
      <td colspan="4" height="35" class="TablaHeader2"> PLAN SEGURO</td>
    </tr>
    <tr  bgcolor="#FDF2AA">
    <td colspan="4"  class="HeaderExcepcion">
      <h:graphicImage library="images" name="errormark.jpg"/>
      <font size="5px" color="#CC0000" >Error de ejecución</font>
      </td>
    </tr>
    <tr >
    <td colspan="3" class="anuncioWarning2">Ocurrio un error al realizar la operación, favor de intentarlo nuevamente, si el error aún se presenta, favor de notificarlo a soporte técnico al 5147-31-00 extensión 6893</td>
    </tr>
    <tr>
      <td height="17" colspan="3" class="TablaHeader2"></td>
    </tr>

</table>
    <h:form id="formerror">
        <h:inputHidden id="valuestack" value="#{errorDisplay.stackTrace}"></h:inputHidden>
    </h:form>
</h:body>

</html>

请注意,motif 允许您调试堆栈跟踪,以便了解隐藏字段中的异常。
让我们看看这个类是如何定义的,

public class ErrorDisplay implements Serializable{

    private static final long serialVersionUID = 6032693999191928654L;
    public static Logger LOG=Logger.getLogger(ErrorDisplay.class);

    public String getContacto() {
        return "";
    }

    public String getStackTrace() {
        FacesContext context = FacesContext.getCurrentInstance();
        Map requestMap = context.getExternalContext().getRequestMap();
        Throwable ex = (Throwable) requestMap.get("javax.servlet.error.exception");

        StringWriter writer = new StringWriter();
        PrintWriter pw = new PrintWriter(writer);
        fillStackTrace(ex, pw);
        LOG.fatal(writer.toString());

        return writer.toString();
    }

    private void fillStackTrace(Throwable ex, PrintWriter pw) {
        if (null == ex) {
            return;
        }

        ex.printStackTrace(pw);

        if (ex instanceof ServletException) {
            Throwable cause = ((ServletException) ex).getRootCause();

            if (null != cause) {
                pw.println("Root Cause:");
                fillStackTrace(cause, pw);
            }
        } else {
            Throwable cause = ex.getCause();

            if (null != cause) {
                pw.println("Cause:");
                fillStackTrace(cause, pw);
            }
        }
    }
}

当您在 facesconfig 文件中完成这个 bean 定义时,该类是如何恢复 StackTrace 并已附加的

<managed-bean>
            <description>
                Bean que sirve para llenar la especificacion de un error. Stacktrace 
            </description>
            <managed-bean-name>errorDisplay</managed-bean-name>
            <managed-bean-class>mx.com.tdc.datos.page.bean.ErrorDisplay</managed-bean-class>
            <managed-bean-scope>session</managed-bean-scope>
        </managed-bean>

,我希望这能起到作用

I made ​​an error page in the site faces and put the stacktrace of the error
This code first put it in the web.xml

<error-page>
                <error-code>500</error-code>
                <location>/errorpage.jsf</location>
</error-page>

While the jsf page had this code

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      >
<h:head>
    <h:outputStylesheet name="EstilosOV.css" library="css" />
    <!-- <h:outputScript name="sincontext.js" library="scripts"/> -->

</h:head>
<h:body >
<table width="338" border="0" align="center" bordercolor="#FFFFFF">

    <tr bgcolor="#1D2F68">
      <td colspan="4" height="35" class="TablaHeader2"> PLAN SEGURO</td>
    </tr>
    <tr  bgcolor="#FDF2AA">
    <td colspan="4"  class="HeaderExcepcion">
      <h:graphicImage library="images" name="errormark.jpg"/>
      <font size="5px" color="#CC0000" >Error de ejecución</font>
      </td>
    </tr>
    <tr >
    <td colspan="3" class="anuncioWarning2">Ocurrio un error al realizar la operación, favor de intentarlo nuevamente, si el error aún se presenta, favor de notificarlo a soporte técnico al 5147-31-00 extensión 6893</td>
    </tr>
    <tr>
      <td height="17" colspan="3" class="TablaHeader2"></td>
    </tr>

</table>
    <h:form id="formerror">
        <h:inputHidden id="valuestack" value="#{errorDisplay.stackTrace}"></h:inputHidden>
    </h:form>
</h:body>

</html>

Note that motif lets you debug the stacktrace for an reazon know which is the exception in the hidden field.
Let's see how the class is defined recovers StackTrace

public class ErrorDisplay implements Serializable{

    private static final long serialVersionUID = 6032693999191928654L;
    public static Logger LOG=Logger.getLogger(ErrorDisplay.class);

    public String getContacto() {
        return "";
    }

    public String getStackTrace() {
        FacesContext context = FacesContext.getCurrentInstance();
        Map requestMap = context.getExternalContext().getRequestMap();
        Throwable ex = (Throwable) requestMap.get("javax.servlet.error.exception");

        StringWriter writer = new StringWriter();
        PrintWriter pw = new PrintWriter(writer);
        fillStackTrace(ex, pw);
        LOG.fatal(writer.toString());

        return writer.toString();
    }

    private void fillStackTrace(Throwable ex, PrintWriter pw) {
        if (null == ex) {
            return;
        }

        ex.printStackTrace(pw);

        if (ex instanceof ServletException) {
            Throwable cause = ((ServletException) ex).getRootCause();

            if (null != cause) {
                pw.println("Root Cause:");
                fillStackTrace(cause, pw);
            }
        } else {
            Throwable cause = ex.getCause();

            if (null != cause) {
                pw.println("Cause:");
                fillStackTrace(cause, pw);
            }
        }
    }
}

and already attached as you finish this bean definition in the file facesconfig

<managed-bean>
            <description>
                Bean que sirve para llenar la especificacion de un error. Stacktrace 
            </description>
            <managed-bean-name>errorDisplay</managed-bean-name>
            <managed-bean-class>mx.com.tdc.datos.page.bean.ErrorDisplay</managed-bean-class>
            <managed-bean-scope>session</managed-bean-scope>
        </managed-bean>

And I hope that this will serve

埋情葬爱 2024-07-19 19:50:14

我遇到了同样的问题,并找到了描述如何在 JSF2 中使用 ExceptionHandler 的链接:

http://jugojava.blogspot.com/2010/09/jsf-2-exception-handling.html

I came to same problem and found link describing how you can use ExceptionHandler in JSF2:

http://jugojava.blogspot.com/2010/09/jsf-2-exception-handling.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文