Java:struts2异常处理

1、struts2中异常处理不是在action类中try…catch,而是把异常抛出去,让struts框架自己处理,程序员需要做的是,当action类中出现异常需要在struts.xml配置文件中进行配置,出现这个异常跳转到哪个物理视图。
2、以前写获取异常是这么写的:

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;
    }
}

3、struts里这么写,只需要把Exception抛出去

public String regist() throws Exception {

		System.out.println(username);
		System.out.println(password);
		System.out.println("你已经成功注册了");
		if (username.equals("1")) {
			throw new SQLException();
		}

		return SUCCESS;
	}

捕获异常的任务则交给struts.xml配置文件

<package name="lee" extends="struts-default">
		<global-results>
			<result name="sql">/WEB-INF/content/exception.jsp</result>
			<result name="root">/WEB-INF/content/exception.jsp</result>
		</global-results>
		<global-exception-mappings>
			<exception-mapping result="sql" exception="java.sql.SQLException"></exception-mapping>
			<exception-mapping result="root" exception="java.lang.Exception"></exception-mapping>
		</global-exception-mappings>
		<action name="*" class="com.action.LoginAction" method="{1}">
			<exception-mapping result="root"
				exception="com.exception.MyException"></exception-mapping>
			<result name="success">/WEB-INF/content/success.jsp</result>
			<result name="error">/WEB-INF/content/error.jsp</result>
		</action>
	</package>

注意:在编写xml文件的时候可能会报错,
这里写图片描述
这个错误是顺序错误,只需要把struts.xml按照提示的顺序写就OK

这种处理方式是不是比较简单明了。

猜你喜欢

转载自blog.csdn.net/tsfx051435adsl/article/details/78515861
今日推荐