和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";
}
结果: