一、基于配置的异常处理
- SpringMVC提供了一个处理控制器方法执行过程中所出现的异常的接口:HandlerExceptionResolver
- HandlerExceptionResolver接口的实现类有:DefaultHandlerExceptionResolver和SimpleMappingExceptionResolver
- SpringMVC提供了自定义的异常处理器SimpleMappingExceptionResolver,使用方式:
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<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>error</title>
</head>
<body>
<h1>error</h1><br>
<span th:text="${ex}"></span>
</body>
</html>
- 测试方法
@RequestMapping("/testExceptionHandler")
public String testExceptionHandler(){
System.out.println(1/0);
return "success";
}
二、基于注解的异常处理
- 添加注解类
@ControllerAdvice
public class ExceptionController {
@ExceptionHandler(ArithmeticException.class)
public String handleArithmeticException(Exception ex, Model model){
model.addAttribute("ex", ex);
return "error";
}
}
- 测试,访问-http://localhost:8080/SpringMvc07/testExceptionHandler