Struts提供了一个更简单的方式来处理未捕获的异常,并将用户重定向到一个专门的错误页面。您可以轻松地Struts配置到不同的异常有不同的错误页面。Struts异常处理实在web层进行的。
步骤:
1.自定义一个相关的异常类:
package cn.itoo.jk.exception;
public class SysException extends Exception {
private String message;
public String getMessage() {
return message;
}
public SysException(String message) {
this.message = message;
}
}
2.导入异常处理页面,往往放到images里面。
3.在struts.xml文件中进行配置
<package name="default" namespace="/" extends="struts-default">
<!-- 配置全局视图 -->
<global-results>
<result name="error">/WEB-INF/pages/error.jsp</result>
</global-results>
<!-- 异常处理框架 -->
<global-exception-mappings>
<exception-mapping result="error" exception="cn.itoo.jk.exception.SysException"></exception-mapping>
<exception-mapping result="error" exception="java.lang.Exception"></exception-mapping>
</global-exception-mappings>
struts的各种action的配置
.....
</package>
当action中
的方法出现异常,并抛出了,框架就会捕获到进而进行页面跳转。
4.如果有struts.xml中引入了其他的struts的配置文件。
其他的配置文件继承default即可default是总struts.xml中package标签中的name值。如下:
<package name="sysadmin" namespace="/sysadmin" extends="default">
5.举个小实例:自定义一个错误
public String toview() throws Exception {
try {
//调用业务层方法,加载部门对象
Dept obj = deptService.get(Dept.class, model.getId());
//将对象放入值栈中
super.push(obj);
} catch (Exception e) {
e.printStackTrace();
throw new SysException("要先选中,在查看!");
}
//跳转页
return "toview";
}
当这个方法出异常时,我们可以很准确的捕获到异常,并给用户很友好的操作提示,并进行了页面跳转。
struts的异常处理使用起来还是挺简单的。