springMvc中@ControllerAdvice的使用
@ControllerAdvice
是一个@Component
,用于定义@ExceptionHandler
,@InitBinder
和@ModelAttribute
方法,适用于所有使用@RequestMapping
方法。
通常情况下配合@ExceptionHandler使用
springMvc中如果单使用@ExceptionHandler
,只能在当前Controller中处理异常。但当配合@ControllerAdvice
一起使用的时候,就可以摆脱那个限制了。
代码:
这样只要在要处理异常的代码逻辑中加入throw new RuntimeException();即会走exceptionHandler这个方法!并返回页面