spring MVC配置异常处理

本文详细介绍了Spring MVC中局部和全局异常处理的配置方法,包括在controller层直接配置异常抛出与捕获,以及在spring-context.xml中进行全局异常配置。通过自定义异常类MyException,实现了对特定异常的定制化处理。

局部异常:在 controller 层直接配置

@PostMapping("dologin")
public String dologin(User user, HttpSession session) {
	if(!"zs".equals(user.getUsername())) {
		throw new MyException("用户名错误!"); // 自定义异常类
		//throw new RuntimeException("用户名错误!");
	}
	if(!"zs".equals(user.getPassword())) {
		throw new MyException("密码错误!"); // 自定义异常类
		//throw new RuntimeException("密码错误!");
	}
	return "redirect:/user/list";
}

// 局部异常处理,只对当前类生效
@ExceptionHandler(value = {MyException.class}) // 自定义异常类
//@ExceptionHandler(value = {RuntimeException.class})
public String handlerException(MyException exception, HttpServletRequest request) {
	request.setAttribute("exception", exception);
	return "error"; // 返回到error.jsp页面
}

全局异常配置:在 spring-context.xml 配置

<!-- 配置全局异常,对整个项目都有效 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
	<property name="exceptionMappings">
		<props>
			<!-- 配置具体的异常,可配置多个 -->
			<!-- <prop key="java.lang.RuntimeException">error</prop> -->
			<!-- 使用自定义异常类,返回到error.jsp页面 -->
			<prop key="com.ssm.exception.MyException">error</prop>
			<!-- <prop key="java.lang.NullPointerException">null</prop> -->
		</props>
	</property>
</bean>

自定义异常类:MyException.java文件

package com.ssm.exception;

public class MyException extends RuntimeException {

	private static final long serialVersionUID = 1L;

	public MyException() {
		super();
	}

	public MyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
	}

	public MyException(String message, Throwable cause) {
		super(message, cause);
	}

	public MyException(String message) {
		super(message);
	}

	public MyException(Throwable cause) {
		super(cause);
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值