SpringMVC的异常处理

1.配置扫描注解和静态资源

<context:component-scan base-package=""></context:component-scan>

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>

2.进行异常处理

	 * @ExceptionHandler 处理的是当前controller方法中所有被requestmapping修饰的方法。在执行期间产生的异常
	 * 	需要在注解的value参数中指定处理的异常种类 或者在方法的参数中指明处理的异常种类 如果都没有该方法无法使用
	 * 
	 * 如果不发生异常 被@ExceptionHandler修饰的方法不会执行
	 * 该方法只能处理注解参数中 value中声名的异常
	 */
@ExceptionHandler(value=IllegalStateException.class)
	//表明处理的哪种响应类型的异常
	@ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR)
	public void resoveException(Exception exception) {
		System.out.println("我是处理异常的方法");
		//exception.printStackTrace();
	}


@RequestMapping("/div")
	public String div(int a,int b) {
		System.out.println("核心的业务功能的方法");
		int c = a/b;
		return "index";
	}
//指定发生异常时要跳转的界面
	@ExceptionHandler(value=ArithmeticException.class)
	public String resovleArithmeticException() {
		System.out.println("发生算数异常");
		return "error";
	}

3.页面显示异常信息

<h1>异常界面</h1>
	<h1><%=exception%></h1>
	<%
		exception.printStackTrace();
	%>
	<h1>
		<%
			StackTraceElement[] elements = exception.getStackTrace();
			for (StackTraceElement element : elements) {
				out.write(element.getClassName() + " " + element.getMethodName() + " " + element.getLineNumber()
						+ "<br>");
			}
		%>
	</h1>

4.用js显示异常

$(function(){
	$.ajax({
		type:"get",
		url:"div?a=10&b=0",
		succes:function(data){
			console.log("data"+JSON.stringify(data));
		}
	})
})

	/ * 同一个controller中不能出现两个方法处理的是同一种异常
	 * 当多个方法处理的异常的种类有继承关系 会执行和发生异常最接近的异常种类的方法
	 * /
@ExceptionHandler(value=ArithmeticException.class)
	@ResponseBody
	public Map<String, String> returnJson(){
		Map<String, String> map = new HashMap<>();
		map.put("code", "501");
		map.put("msg", "b能为0");
		return map;
	}
@ExceptionHandler(value=Exception.class)
	@ResponseBody
	public Map<String, String> returnJson2(){
		Map<String, String> map = new HashMap<>();
		map.put("code", "500");
		map.put("msg", "b能为0");
		return map;
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值