它的概念是建立异常类型与错误页面之间的映射关系,即出错之后,跳转到指定的页面。
1、属性
它有以下几个属性:
- exceptionsMapping:异常类型与页面之间的映射关系,key值为异常类型,value值为页面,它会经过ViewResolver处理。
- excludedExceptions:排除这些异常。
- defaultErrorView:若抛出的异常类型在exceptionsMapping找不到映射关系,使用默认的页面。抛出的异常类型不包含excluedExceptions中的值。
- defaultStatusCode:默认的状态码
2、使用
使用SimpleMappingExceptionResolver的步骤如下:
- 第一步,创建SimpleMappingExceptionResolver对象,配置上述的属性
- 第二步,注册。注解方式是通过重写configureHandlerExceptionResolvers方法。Xml方式是通过配置SimpleMappingExceptionResolver的bean。
3、示例
第一步,创建exception.properties,建立异常与页面的映射关系
# 算术异常 java.lang.ArithmeticException = error/arithmeticException
第二步,创建SimpleMappingExceptionResolver对象,加载exception.properties文件,并配置上述属性
/**
*
* @Title: getSimpleMappingExceptionResolver
* @Description:配置SimpleMappingExceptionResolver
* @return
*/
private SimpleMappingExceptionResolver getSimpleMappingExceptionResolver() {
// 创建SimpleMappingExceptionResolver
SimpleMappingExceptionResolver simple = new SimpleMappingExceptionResolver();
// 加载exception.properties
Properties exceptions = new Properties();
// 添加算术异常,可以改进为Properties文件
exceptions.put("java.lang.ArithmeticException", "error/arithmeticException");
// 添加异常与页面的映射关系
simple.setExceptionMappings(exceptions);
// 排除异常,排除空指针异常
simple.setExcludedExceptions(NullPointerException.class);
// 设置默认的异常跳转页面
simple.setDefaultErrorView("error/error.jsp");
// 设置默认的异常码
simple.setDefaultStatusCode(999);
return simple;
}
第三步,注册,重写configureHandlerExceptionResolvers方法。方法的参数为HandlerExceptionResolver集合,把新创建的对象添加到集合中
/**
*
* 添加异常处理解析器
*
*/
@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
// 注册SimpleMappingExceptionResolver
resolvers.add(getSimpleMappingExceptionResolver());
}
第四步,测试,在Controller方法中运行1/0,抛出算术异常,验证结果。