Struts2 声明式异常处理

在struts2应用程序中我们可以使用使用try catch语句来捕获异常,而后对异常进行处理,最后使用return 一个控制符告诉struts转到对应的视图;而另一方面struts2支持声明式异常处理,它是通过拦截器(interceptor)来处理声明式异常的,我们可以在Action中直接抛出异常而交给struts2来处理,当然,这需要我们在DAO、Service、Action层都需要抛出相应的异常,然后再在struts2的xml文件中配置,由于抛出同样的异常的处理方法通常都一样,所以如果能在xml中配置全局异常,将会使得开发便捷性大大提高。

以前的异常捕获可能是这样的:

/**
 * New User Register 
 * @return
 */
public String add() {
    if(!Common.isEmpty(user)){
        try {
            userService.add(user);
            return SUCCESS;
        } catch (SQLException e) {
            e.printStackTrace();
            return ERROR;
        } catch (InvalidInputException e) {
            e.printStackTrace();
            System.out.println("An Error occur when adding a user");
            return ERROR;
        }
    }
}

 

采用struts2的声明式异常处理:

首先,上面的代码的try catch 就可以全都不要了,但是,得在方法上新加throws语句告诉struts程序可能会抛出的异常:

/**
 * New User Register 
 * @return
 */
public String add() throws SQLException,InvalidInputException{
    if(!Common.isEmpty(user)){
        userService.add(user);
        return SUCCESS;
    }
}

 捕获异常的任务就完全交给struts了。需要配置。配置文件还是比较容易理解的:

<package name="admin" extends="struts-default">
    <global-results>
        <result name="sql">/error.jsp</result>
        <result name="invalidinput">/inputError.jsp</result>
    </global-results>
    <global-exception-mappings>
        <exception-mapping result="sql" exception="java.sql.SQLException" />
        <exception-mapping result="invalidinput" exception="com.user.exception.InvalidInputException" />
    </global-exception-mappings>
    <action name="user_*" class="userAction" method="{1}">
        <result >/index.jsp</result>
        <result name="error">/error.jsp</result>
        <!--<exception-mapping result="sql" exception="java.sql.SQLException" />-->
    </action>
</package>

       * exception: 异常类型

  * result:指定Action出现该异常时,系统转入result属性所指向的结果。

如上所述,我们看到在package中有global-result和global-exception-mapping配合起来使用的,也有放在action中单独使用的exception-mapping (注释部分),读者可根据情况选择使用

需要说明的是,

  1. 使用global-exception-mapping必先定义好global-result,否则编译器会报错;
  2. 如若出现异常,struts2会先查找action中的exception-mapping,如果找到对应的结果则返回,如果找不到则查找global-exception-mapping;
  3. 如果局部(当前)Action、和全局结果集存在相同的<result>,则使用最近的那个结果

异常的组织与分类:

所有业务异常类派生于自定义的BaseException基类。

  1. 原则上,要进行相同处理的异常分为一类,用ERROR_CODE标识不同。
  2. 出错信息统一写在errors.properties,以ERROR_CODE为主键,支持i18N,由基类提供默认的getMessage()函数。
  3. Servlet规范里的异常控制
  4. 按error-code统一定义错误页面,404.jsp/error.jsp 按异常类型定义单独错误页面

其中jsp的异常在exception 变量中.
servlet的异常在(Exception)request.getAttribute("javax.servlet.error.exception")
spring的异常在(Exception) request.getAttribute("exception")
使用 (String) request.getAttribute("javax.servlet.error.request_uri")获得 request_uri
使用 logger.error(exception.getMessage(), exception); 记录整个异常栈

猜你喜欢

转载自linbaolee.iteye.com/blog/2077816
今日推荐