springmvc异常信息的解读

和Struts2一样,springmvc也有异常处理机制,但是实现起来比struts2容易,我们struts2要去struts.xml文件配置exception-mapping,然后自定义个异常

       springmvc实现就相对比较简单

   定义一个异常信息类

package com.asiainfo.springmvc.exception;

import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.asiainfo.springmvc.controller.BaseController;


@ControllerAdvice    //是一个组件修饰注解,可以被springmvc扫描到
public class DefineException {
	
	private static final Logger logger = Logger.getLogger(BaseController.class);
	
	@ExceptionHandler({ArithmeticException.class})//这里是数组,可以加入多个异常类,也可以是自定义的类
	public ModelAndView dealException(Exception e){
		
		logger.debug(e);
		
		ModelAndView mv = new ModelAndView();
		
		mv.addObject("exception", e.getMessage());//可以自己来定义异常信息返回到页面
		
		mv.setViewName("error");
		
		return mv;
	}
}
测试方法:
@RequestMapping("/testException")
	public String testException(@RequestParam("num") int num){
		
		int i = 10/num;
		
		return "success";
	}
结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值