• 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>
    

    参考资料

  • 相关阅读:
    SDP(12): MongoDB-Engine
    SDP(11):MongoDB-Engine功能实现
    SDP(10):文本式大数据运算环境-MongoDB-Engine功能设计
    React Native(五)——获取设备信息react-native-device-info
    React Native(四)——顶部以及底部导航栏实现方式
    去掉a标签
    React Native(三)——推送jpush-react-native
    react native (一)
    《JavaScript 秘密花园》
    正则表达式(overall)
  • 原文地址:https://www.cnblogs.com/linkworld/p/7783087.html
Copyright © 2020-2023  润新知