SpringMVC之异常处理器的使用
[*]SpringMVC的异常处理器是处理控制器方法执行过程出现的异常。
[*]SpringMVC提供了一个处理异常的接口HandlerExceptionResolver。
[*]HandlerExceptionResolver接口有两个实现类:
DefaultHandlerExceptionResolver实现类和SimpleMappingExceptionResolver实现类。
DefaultHandlerExceptionResolver实现类是SpringMVC默认异常处理器。
SimpleMappingExceptionResolver实现类是简易异常处理器,我们一般自定义配置异常处理策略就是使用该异常处理器。
基于xml文件配置异常处理器
配置异常处理器
<bean >
<property name="order" value="1"/>
<property name="exceptionMappings">
<props>
<prop key="java.lang.ArithmeticException">error</prop>
<prop key="java.lang.NullPointerException">error</prop>
</props>
</property>
<property name="exceptionAttribute" value="ex"/>
</bean>创建视图
<a th:target="_blank" href="https://www.cnblogs.com/@{/test/error}">测试异常处理器</a><br/><!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>错误</title>
</head>
<body>
<h1>error.html</h1>
<hr/>
<a th:text="${ex}"></a>
</body>
</html>编写控制器方法
@GetMapping("/test/error")
public String testError() {
//出现异常
System.out.println(10/0);
return "success";
}测试
发送访问/test/error控制器方法的请求,控制器方法执行过程中出现异常处理器中配置的异常策略,跳转到指定异常视图。
基于注解配置异常处理器
@ControllerAdvice //将当前类标识为异常处理的组件
public class ExceptionController {
//@ExceptionHandler用于设置所标识方法处理的异常
//ex表示当前请求处理中出现的异常对象
@ExceptionHandler(value = {ArithmeticException.class})
public ModelAndView handleArithmeticException(Exception ex) {
ModelAndView mad = new ModelAndView();
mad.addObject("ex",ex);
mad.setViewName("error");
return mad;
}
@ExceptionHandler(value = {NullPointerException.class})
public String handleNullPointerException(Exception ex,Model model) {
model.addAttribute("ex",ex);
return "error";
}
}
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页:
[1]