异常处理器
1、基于配置的异常处理
SpringMVC 提供了一个处理控制器方法执行过程中所出现的异常的接口:HandlerExceptionResolver
HandlerExceptionResolver 接口的实现类有:DefaultHandlerExceptionResolver 和 SimpleMappingExceptionResolver
SpringMVC 提供了自定义的异常处理器 SimpleMappingExceptionResolver,使用方式:
<a th:href="@{/testExceptionHandler}">测试异常</a><br/>
<!--配置异常处理-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!--跳转到error页面-->
<prop key="java.lang.ArithmeticException">error</prop>
</props>
</property>
<!--value:设置将异常信息共享到请求域中的键-->
<property name="exceptionAttribute" value="ex"></property>
</bean>
error.html 页面:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
出现错误
<p th:text="${ex}"></p>
</body>
</html>
控制器:
@RequestMapping("/testExceptionHandler")
public String testExceptionHandler(){
System.out.println(3/0);
return "success";
}
2、基于注解的异常处理
@ControllerAdvice 将当前类标识为异常处理的组件
<a th:href="@{/testExceptionHandler}">测试异常</a><br/>
@ControllerAdvice
public class ExceptionController {
//@ExceptionHandler用于设置所标识方法处理的异常
@ExceptionHandler(value = {ArithmeticException.class, NullPointerException.class})
//ex表示当前请求处理中出现的异常对象
public String testException(Exception ex, Model model){
model.addAttribute("ex", ex);
return "error";
}
}