Fork me on GitHub

Struts2 声明式异常处理

1. 声明式异常捕捉

  1. Struts2 的异常处理机制是通过 struts.xml 文件中配置 <exception-mapping> 元素完成的,
    配置该元素时,需要指定两个属性:
    • exception: 异常类型;
    • result: 指定逻辑视图名称;
  2. 根据 <exception-mapping> 出现的位置,异常映射分为两种:
    • 局部异常映射:将<excepion-mapping>元素作为<action>元素的子元素配置;
    • 全局异常映射:将<exception-mapping>元素作为<global-exception-mappings>元素的子元素
    • 全局异常映射对所有的 Action 类都有效,但局部异常映射仅对该异常映射所在的 Action 有效;
// 第一种方式: 手动处理异常 try/catch
public String update(){

    Customer cust = new Customer();
    cust.setId(id);

    try{
        customerService.update(cust);
        return SUCCESS;
    }catch(SQLException e){
        e.printStackTrace();
        return ERROR;
    }catch(InvalidInputException e){
        e.printStackTrace();
        System.out.println("非法输入");
        return ERROR;
    }
}

// 第二种方式: 声明式异常处理
public String update() throws SQLException, InvalidInputException{
    Customer cust = new Customer();
    cust.setId(id);

    customerService.update(article);
    return SUCCESS;
}

// struts.xml 配置异常
<package name="crm" namespace="/" extends="struts-default">
    <global-results>
        <result name="sql">/internal_Error.jsp</result>
        <result name="invalidInput">/invalid_input.jsp</result>
        <result name="naming">/internal_Error.jsp</result>
    </global-results>

    <global-exception-mappings>
        <exception-mapping result="sql" exception="java.sql.SQLException"/>
        <exception-mapping result="invalidInput"
                            exception="cn.itcast.exception.InvalidInputException">
        </exception-mapping>

        <exception-mapping result="naming" exception="javax.naming.NamingException"/>
    </global-exception-mappings>
    <action name="customer_*" class="cn.itcast.web.action.CustomerAction" method={1}>
        <result name="success">/success.jsp</result>
    </action>
</package>


// error.jsp
// 使用 struts2 的标签输出异常信息:
//   输出异常的 message 属性信息:<s:property value="exception.message"/>
//   输出异常堆栈信息: <s:property value="exceptionStack"/>

<body>
    抱歉,系统繁忙,请稍候在试!
    <s:property value="exception.message"/>
</body>

参考资料

posted @ 2017-11-04 13:10  小a的软件思考  阅读(722)  评论(0编辑  收藏  举报