现在的位置: 首页 > 综合 > 正文

Struts2的声明式异常处理

2014年04月29日 ⁄ 综合 ⁄ 共 904字 ⁄ 字号 评论关闭

在struts2应用程序中你还在使用try catch语句来捕获异常么?如果是这样的,那你OUT啦!struts2支持声明式异常处理,可以再Action中直接抛出异常而交给struts2来处理,当然需要我们在xml文件中配置,由于抛出同样的异常的处理方法通常都一样,所以如果能在xml中配置全局异常,将会使得开发便捷性大大提高。

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

/**
 *
执行更新
 *
 *
@return
 */
public String
update() {
    Article
article =
new Article();
    article.setContent(content);
    article.setTitle(title);
    article.setId(id);
    try {
        articleService.update(article);
        return SUCCESS;
    }
catch (SQLException
e) {
        e.printStackTrace();
        return ERROR;
    }
catch (InvalidInputException
e) {
        e.printStackTrace();
        System.out.println("输入非法");
        return ERROR;
    }
}

这种方式是完全的手动处理异常,一来不够简洁明快,而且还不容易维护,毕竟如果修改了这些代码都需要再次编译。

采用struts2的声明式异常处理就会简单很多了。

首先,上面的代码的try catch 就可以全都不要了,但是,当然,得新加throw语句抛出异常:

/**
 *
执行更新
 *
 *
@return
 *
@throws InvalidInputException
 *
@throws SQLException
 */
public String
update()
throws SQLException,
InvalidInputException {
    Article
article =
new Article();

抱歉!评论已关闭.