这篇文章主要介绍了springMVC基于配置的异常处理器怎么用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇springmvc基于配置的异常处理器怎么用文章都会有所收获,下面我们一起来看看吧。一、基于配置的异常
这篇文章主要介绍了springMVC基于配置的异常处理器怎么用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇springmvc基于配置的异常处理器怎么用文章都会有所收获,下面我们一起来看看吧。
SpringMVC 提供了一个处理控制器方法执行过程中所出现的异常的接口:HandlerExceptionResolver。
HandlerExceptionResolver接口的实现类有:
DefaultHandlerExceptionResolver,这个是默认使用的处理器,之前遇到的一些异常,其实springMVC 都已经给我们处理过了。
SimpleMappingExceptionResolver,这个可以让我们自定义异常处理。当出现指定的异常,可以设置返回新的视图。
使用SimpleMappingExceptionResolver,在springMVC的配置文件中:
<!--配置异常处理--> <bean class="org.springframework.WEB.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="java.lang.ArithmeticException">error</prop> </props> </property> </bean>
示例里使用的一个处理运算异常的类ArithmeticException,里面的值 error 表示异常后跳转的视图。
对应的,新建一个error.html页:
<!DOCTYPE html><html lang="en" xmlns:th="Http://www.thymeleaf.org"><head> <meta charset="UTF-8"> <title>error</title></head><body>出现错误</body></html>
接下来,造一个异常:
@RequestMapping("/testExceptionHandler") public String testExceptionHandler() { System.out.println(1/0); return "success"; }
正常情况下这个处理器会跳转到 success 页,但是里面有个 1/0的异常,所以会按照配置跳转到 error 页。
重新部署,测试一下,访问http://localhost:8080/springmvc/testExceptionHandler:
成功跳转到 error 页。
此外,还可以继续属性exceptionAttribute,设置一个key用来存放异常信息,默认存在当前的请求域中:
<!--配置异常处理--> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="java.lang.ArithmeticException">error</prop> </props> </property> <!--exceptionAttribute属性设置一个属性名,将出现的异常信息在请求域中进行共享--> <property name="exceptionAttribute" value="ex"></property> </bean>
那么在 error 页中就可以使用到ex来获取异常信息了。
<!DOCTYPE html><html lang="en" xmlns:th="http://www.thymeleaf.org"><head> <meta charset="UTF-8"> <title>error</title></head><body>出现错误<p th:text="${ex}"></p></body></html>
重新部署,刷新下页面:
springmvc 同样也提供了一套注解,通过注解方式也可以实现上述的异常处理。
新建一个控制器 ExceptionController:
//@ControllerAdvice将当前类标识为异常处理的组件@ControllerAdvicepublic class ExceptionController { //@ExceptionHandler 用于设置所标识方法处理的异常 @ExceptionHandler(value = {ArithmeticException.class, NullPointerException.class}) public String testException(Exception ex, Model model){ // ex表示当前请求处理中出现的异常对象,放到请求域中 model.addAttribute("ex", ex); return "error"; }}
@ControllerAdvice将当前类标识为异常处理的组件。
ex表示当前请求处理中出现的异常对象,用Model放到请求域中。
现在注释掉配置文件里的处理器,重新部署下,刷新http://localhost:8080/springmvc/testExceptionHandler:
依然可以。
关于“SpringMVC基于配置的异常处理器怎么用”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“SpringMVC基于配置的异常处理器怎么用”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注编程网精选频道。
--结束END--
本文标题: SpringMVC基于配置的异常处理器怎么用
本文链接: https://www.lsjlt.com/news/330372.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0