十二、异常处理
1、基于配置的异常处理
SpringMVC提供了一个处理控制路方法执行过程中所出现的异常的接口:HandlerExceptionResolver
HandlerExceptionResolver接口的实现类有:DefaultHandlerExceptionResolver和SimpleMappingExceptionResolver
测试步骤:
1)在templates目录下新建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>
2)SpringMVC提供了自定义的异常处理器SimpleMappingExceptionResolver,使用方式:
<!--配置异常处理--> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <!--设置键值 key中设置指定的异常,此处的ArithmeticException 为数学异常 双标签<prop>xxx<prop>中的xxx为value值,表示一 个新的视图名称,当出现指定异常时,跳转到该页面。此 处的error表示出现异常时跳转到error页面 --> <props> <prop key="java.lang.ArithmeticException">error</prop> </props> </property> <!--设置在视图中展现异常信息,value的作用是设置将异常信息共享到请求域中的键--> <property name="exceptionAttribute" value="ex" /> </bean>
3)index.html设置
<a th:href="@{/testExceptionHandler}">测试异常处理</a><br>
4)控制器设置
//异常处理测试 @RequestMapping("/testExceptionHandler") public String testExceptionHandler(){ System.out.println(1/0); return "error"; }
2、基于注解的异常处理
测试步骤:
1)在templates目录下新建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>
2)index.html设置
<a th:href="@{/testExceptionHandler}">测试异常处理</a><br>
3)在controller包下新建ExceptionController类,用于编写异常控制
/** * @ExceptionHandler 表示如果遇到ArithmeticException.class或者 * NullPointerException.class异常就会通过下 * 面注解所标识的方法来作为新的控制器方法来执行 */ @ExceptionHandler(value = {ArithmeticException.class, NullPointerException.class}) //使用Exception ex来获取异常信息,然后使用Model来共享数据 public String testException(Exception ex, Model model){ model.addAttribute("ex", ex); return "error"; }