SpringMVC中的异常处理

本文详细介绍了在Spring MVC框架中实现局部和全局异常处理的方法。通过使用@ExceptionHandler注解进行局部异常处理,以及在配置文件中设置SimpleMappingExceptionResolver来实现全局异常处理。文章还提供了具体的代码示例和页面展示效果。

 对于异常处理我们分为局部异常处理,和全局异常处理,下面我们开始

一、局部异常处理

1、 局部异常使用@ExceptionHandler实现,@ExceptionHandler可以指定多个异常。

package com.bdqn.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class local {
	
	@RequestMapping("local.html")
	public String  demo1(){
		//throw new RuntimeException("用户名或密码输入不正确!");
		throw new NullPointerException("我是空指针异常");
	}
	
	@ExceptionHandler(value={RuntimeException.class,NullPointerException.class})
	public String exception(RuntimeException e,HttpServletRequest request){
		request.setAttribute("e",e);
		return "error_local";
	}

}

    注意: jsp页面使用${e.message}输出异常信息

2、页面展示效果

二、全局异常处理 

 1、在springmvc_servlet.xml中配置全局异常

<!-- 全局异常处理 -->
	<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
		<property name="exceptionMappings">
			<props>
				<prop key="java.lang.RuntimeException">error</prop>
			</props>
		</property>
	</bean>

2、在控制器中编写异常类

package com.bdqn.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class global {
	
	@RequestMapping("global.html")
	public String  demo2(){
		throw new RuntimeException("我是全局异常");
	}

}

3、在jsp页面使用${exception.message }展示数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值