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>
    

    参考资料

  • 相关阅读:
    牛客网 2018年东北农业大学春季校赛 L题 wyh的天鹅
    牛客网 2018年东北农业大学春季校赛 I题 wyh的物品
    记cccc天梯赛第三届决赛
    noi.openjudge 1.13.15
    Java连接Oracle数据库的三种连接方式
    SSH框架总结(框架分析+环境搭建+实例源码下载)
    深入浅出MyBatis:JDBC和MyBatis介绍
    每个 Java 开发者都应该知道的 5 个注解
    高效Web开发的10个jQuery代码片段
    编写优秀jQuery插件的10个技巧
  • 原文地址:https://www.cnblogs.com/linkworld/p/7783087.html
Copyright © 2011-2022 走看看