SpringMVC之异常处理器

文章目录


前言

SpringMVC提供了一个处理控制器方法执行过程中所出现的异常的接口:HandlerExceptionResolver。

HandlerExceptionResolver接口的实现类有:DefaultHandlerExceptionResolver(默认的)和

SimpleMappingExceptionResolver(自定义的)。


一、基于配置的异常处理

xml 复制代码
<bean
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!--
properties的键表示处理器方法执行过程中出现的异常
properties的值表示若出现指定异常时,设置一个新的视图名称,跳转到指定页面
-->
<prop key="java.lang.ArithmeticException">error</prop>
</props>
</property>
<!--
exceptionAttribute属性设置一个属性名,将出现的异常信息在请求域中进行共享
-->
<property name="exceptionAttribute" value="ex"></property>
</bean>

二、基于注解的异常处理

这里配置了两个异常,出现其中一个异常后跳转到error页面。

java 复制代码
//@ControllerAdvice将当前类标识为异常处理的组件
@ControllerAdvice
public class ExceptionController {
	//@ExceptionHandler用于设置所标识方法处理的异常
	@ExceptionHandler(value = {ArithmeticException.class,NullPointerException.class})
	//ex表示当前请求处理中出现的异常对象
	public String handleArithmeticException(Exception ex, Model model){
	model.addAttribute("ex", ex);
	return "error";
	}
}

总结

以上就是异常处理器的配置,比较简单。

相关推荐
木木子99993 小时前
业务架构、应用架构、数据架构、技术架构
java·开发语言·架构
qq_5470261795 小时前
Flowable 工作流引擎
java·服务器·前端
鼓掌MVP6 小时前
Java框架的发展历程体现了软件工程思想的持续进化
java·spring·架构
编程爱好者熊浪6 小时前
两次连接池泄露的BUG
java·数据库
lllsure6 小时前
【Spring Cloud】Spring Cloud Config
java·spring·spring cloud
拽着尾巴的鱼儿6 小时前
fixed-bug:JPA 关联关系的对象序列化循环引用问题
spring·bug·jpa
鬼火儿7 小时前
SpringBoot】Spring Boot 项目的打包配置
java·后端
NON-JUDGMENTAL7 小时前
Tomcat 新手避坑指南:环境配置 + 启动问题 + 乱码解决全流程
java·tomcat
cr7xin7 小时前
缓存三大问题及解决方案
redis·后端·缓存
chxii7 小时前
Maven 详解(上)
java·maven