1 基于xml配置的异常处理器
SpringMVC提供了一个处理器的控制方法,执行过程中所出现的异常的接口: HandleExceptionResolve
HandleExceptionResolve 接口的实现类有:DefaultHandleExceptionResolve和SimpleMappingExceptionResolver
SpringMVC 也提供了自定义的异常处理器 SimpleMappingExceptionResolver
接口: HandleExceptionResolve: 只提供了一个抽象方法 resolveException解析异常,如果控制器方法中在执行时出现了指定异常
返回modelandview
DefaultHandleExceptionResolve:默认的异常处理解析器
SimpleMappingExceptionResolver:当我们不想用默认的 就可以配置这个
将自定义的异常处理器 配置到配置文件中,
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<!--设置属性值,实现了view 的页面跳转-->
<props>
<!-- key-value-->
<!-- key设置要处理的异常,
value设置出现该异常要跳转到的页面对应的逻辑视图-->
<prop key="java.lang.ArithmeticException">error</prop>
</props>
</property>
<!--设置共享到请求域中的异常信息的属性名-->
<property name="exceptionAttribute" value="ex"></property>
</bean>
逻辑视图:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>错误</title>
</head>
<body>
<h1>error.html</h1>
<p th:text="${ex}"></p>
</body>
</html>
2 基于注解配置异常处理器
// 将当前类表示为异常处理的组件
@ControllerAdvice
public class ExceptionController {
//设置要处理的异常信息
@ExceptionHandler(ArithmeticException.class) //异常处理
//出现异常就会执行下面的方法
//ex来表示控制器方法所出现的异常
public String handleException(Throwable ex, Model model){
model.addAttribute("ex",ex);
return "error";
}
}
二者去方便的即可