在使用spring mvc开发时,在Controller中一定会遇到各种异常,如果在每个可能出现异常的地方都对异常进行捕获,这样不仅工作量大不利于提高开发效率,还会对项目的维护产生负面影响,还好spring mvc支持对异常进行集中处理,下面用一个小例子来了解怎么使用
由于我喜欢使用注解,不喜欢用配置文件,所以这个例子就是用注解实现,这样的好处是代码比较灵活,也比较整洁(个人观点)
首先自定义一个Controller的父类,需要捕获异常的Controller继承此类就可以了
public class BaseController {
/**
* 使用@ExceptionHandler注解,继承此类的Controller发生异常时会自动执行该方法
* @param request
* @param e
* @return
*/
@ExceptionHandler
public String exception(HttpServletRequest request, Exception e) {
//对异常进行判断做相应的处理
if(e instanceof NullPointerException){
return "/error1.html";
}else if(e instanceof IllegalArgumentException){
return "/error2.html";
}else{
return "/error3.html";
}
}
}
使用方法
@Controller
public class TestAction extends BaseController{
@RequestMapping(value = "/manager/test1f.aspx", method = { RequestMethod.GET, RequestMethod.POST })
public void test1f(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
throw new NullPointerException();
}
}
这样访问 /manager/test1f.aspx时会抛出异常并被处理,跳转至 /error1.html
如果是处理不同情况下的异常,可以自定义多个父Controller,根据不同业务继承对应的Controller就可以了,很灵活