在struts的核心jar当中我们可以找到struts-default.xml配置文件。
一个请求到来首先会被StrutsPrepareAndExecuteFilter过滤,在其中会调用action。struts拦截器就是在调用action之前会调用interceptor,然后interceptor再调用action。
在Struts2里面,我们的异常的处理就是被一个拦截器实现。我们配置package,它的父类都来源于struts-default.xml,在struts-default配置了很多拦截器,我们所有的action都会被这些拦截器过滤,在其中我们也可以找到处理异常的拦截器ExceptionMappingInterceptor。
声明式异常处理原理:action抛出了异常会被ExceptionMappingInterceptor捕捉到。ExceptionMappingInterceptor处理异常的逻辑看后面源码:
让我们来看ExceptionMappingInterceptor中部分源码:
public String intercept(ActionInvocation invocation) throws Exception {
String result;
try {
result = invocation.invoke();//在这里面会调用action,如果action抛出了异常,会被捕捉到
} catch (Exception e) {
if (isLogEnabled()) {
handleLogging(e);
}
//获取struts.xml配置文件中配置的Exception Mapping,返回的是一个List
List<ExceptionMappingConfig> exceptionMappings = invocation.getProxy().getConfig().getExceptionMappings();
//在集合List中是否存在action抛出这个异常,如果存在,返回Exception Mapping 对应result
String mappedResult = this.findResultFromExceptions(exceptionMappings, e);
if (mappedResult != null) {//看result是否为null
result = mappedResult;
publishException(invocation, new ExceptionHolder(e));//把异常的信息放入Value Stack中
} else {
throw e;
}
}
return result;
}