在Spring MVC中,所有用于处理在请求映射和请求处理过程中抛出的异常的类,都要实现 HandlerExceptionResolver 接口。
一个基于Spring MVC的Web应用程序中,可以存在多个实现了HandlerExceptionResolver的异常处理类,他们的执行顺序,由其order属性决定, order值越小,越是优先执行, 在执行到第一个返回不是null的ModelAndView的Resolver时,不再执行后续的尚未执行的Resolver的异常处理方法。
平常开发的时候,我一般都会配置:,使用了这个配置标签,SpringMVC会默认配置:
一、ExceptionHandlerExceptionResolver接口
在该 controller 类中使用@ExceptionHandler(value= { 大Class数组 }) : 根据异常需求写大Class
//http://127.0.0.1:8080/sshweb/textex?num=1
@RequestMapping(value="/textex")
public String textex(@RequestParam("num") int num) {
System.out.println("商为:" + 10/num);
return "redirect: /sshweb/users";
}
// 必须使用ModelAndView, 而不是String, 否则 无法渲染试图
@ExceptionHandler(value= {ArithmeticException.class})
public ModelAndView HandlerEX(Exception e) {
System.out.println("出异常了---" + e.getMessage());
ModelAndView mv = new ModelAndView();
mv.addObject("ex", e.getMessage());
mv.setViewName("error");
return mv;
}
要把异常信息注入到 error.jsp 页面, 必须返回 ModelAndView。
错误页面
异常信息为: ${ex }
需要注意的是,上面例子中的ExceptionHandler方法的作用域,只是在本Controller类中。
如果需要使用ExceptionHandler来处理全局的Exception,则创建一个类需要使用@ControllerAdvice注解。
自定义 HandlerGlobalEX 类: 处理全局的(ArithmeticException.class,RuntimeException.class)
@ControllerAdvice
public class HandlerGlobalEX{
// 必须使用ModelAndView, 而不是String, 否则 无法渲染试图
@ExceptionHandler(value= {ArithmeticException.class,RuntimeException.class})
public ModelAndView HandlerEX(Exception e) {
System.out.println("出异常了---" + e.getMessage());
ModelAndView mv = new ModelAndView();
mv.addObject("ex", e.getMessage());
mv.setViewName("error");
return mv;
}
}
二、SimpleMappingExceptionResolver,不用自己写处理异常类,直接配置就ok:
1) springmvc.xml 配置文件中配置异常处理器:
error-runtime
error-arith
SimpleMappingExceptionResolver 会把异常信息注入到error.jsp页面,默认异常信息的引用名:exception,这个默认名字是可以通过 修改.
2) error-arith.jsp :
算数异常
异常信息为: ${ex }
异常信息为: ${exception }
异常信息为: ${ex.message }
附一张图(来自网络):
SpringMVC的请求处理的全过程示意图