zoukankan      html  css  js  c++  java
  • 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>
    

    参考资料

  • 相关阅读:
    jQuery属性--html([val|fn])、text([val|fn])和val([val|fn|arr])
    JavaScript--常用的输出方式
    jQuery筛选--hasClass(class)和eq(index|-index)
    jQuery筛选--first()和last()
    EasyUI学习-----表格DataGrid获取数据的方式
    EasyUI学习-----创建DataGrid及冻结列的两种方式
    jQuery属性--addClass()和removeClass()
    jQuery工具--jQuery.isNumeric(value)和jQuery.trim(str)
    jQuery工具--$.each()和$.merge()
    jQuery事件--change([[data],fn])、on(events,[selector],[data],fn)和hover([over,]out)
  • 原文地址:https://www.cnblogs.com/linkworld/p/7783087.html
Copyright © 2011-2022 走看看