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";
	}
}

总结

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

相关推荐
江湖中的阿龙1 分钟前
23种设计模式
java·开发语言·设计模式
可可嘻嘻大老虎2 分钟前
SpringBoot拦截器防重复提交实战
java·spring boot·后端
RainCityLucky7 分钟前
Java Swing 自定义组件库分享(十一)
java·笔记·后端
cheems95277 分钟前
[开发日记]Spring Boot + MyBatis-Plus 抽奖系统排障实录:从 JWT 被拦截到雪花 ID 失控,我是怎样一步步修通登录与人员列表的
spring boot·后端·mybatis
ch.ju7 分钟前
Java Programming Chapter 4——The set method assigns a value to the property.
java·开发语言
Sam_Deep_Thinking8 分钟前
SaaS多租户业务差异化:扩展点机制的设计与实现
java·架构
古城小栈9 分钟前
Rustix库:Rust 系统编程 的 基石
开发语言·后端·rust
我登哥MVP12 分钟前
Spring Boot 从“会用”到“精通”:Rest风格原理
java·spring boot·后端·spring·maven·intellij-idea·mybatis
love_muming13 分钟前
数据结构入门:栈与队列详解
java·开发语言·数据结构
Je1lyfish13 分钟前
CMU15-445 (2025 Fall/2026 Spring) Project#4 - Concurrency Control
开发语言·数据库·c++·笔记·后端·算法·系统架构