Spring MVC中@ControllerAdvice注解实现全局异常拦截

@ControllerAdvice注解一般用作处理系统error,拦截出错信息,返回报错提示界面,防止用户看到一推出错信息!  
Java代码   收藏代码
  1. import org.springframework.ui.Model;  
  2. import org.springframework.web.bind.WebDataBinder;  
  3. import org.springframework.web.bind.annotation.ControllerAdvice;  
  4. import org.springframework.web.bind.annotation.ExceptionHandler;  
  5. import org.springframework.web.bind.annotation.InitBinder;  
  6. import org.springframework.web.bind.annotation.ModelAttribute;  
  7. import org.springframework.web.context.request.NativeWebRequest;  
  8.   
  9. /**  
  10.  * 1、通过@ControllerAdvice注解可以将对于控制器的全局配置放在同一个位置。 
  11.  * 2、注解了@Controller的类的方法可以使用@ExceptionHandler、@InitBinder、@ModelAttribute注解到方法上。 
  12.  * 3、@ControllerAdvice注解将作用在所有注解了@RequestMapping的控制器的方法上。 
  13.  * 4、@ExceptionHandler:用于全局处理控制器里的异常。 
  14.  * 5、@InitBinder:用来设置WebDataBinder,用于自动绑定前台请求参数到Model中。 
  15.  * 6、@ModelAttribute:本来作用是绑定键值对到Model中,此处让全局的@RequestMapping都能获得在此处设置的键值对 
  16.  *  
  17.  * @author zx 
  18.  * @date 2017-03-10 
  19.  */  
  20. @ControllerAdvice  
  21. public class GlobalControllerInterceptor   
  22. {  
  23.     @ModelAttribute  
  24.     //应用到所有@RequestMapping注解方法  
  25.     //此处将键值对添加到全局,注解了@RequestMapping的方法都可以获得此键值对  
  26.     public void addUser(Model model) {   
  27.         model.addAttribute("msg""此处将键值对添加到全局,注解了@RequestMapping的方法都可以获得此键值对");  
  28.     }    
  29.     
  30.     @InitBinder    
  31.     //应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器  
  32.     //用来设置WebDataBinder,用于自动绑定前台请求参数到Model中。  
  33.     public void initBinder(WebDataBinder binder) {    
  34.     }    
  35.     
  36.     @ExceptionHandler(Exception.class)    
  37.     //应用到所有@RequestMapping注解的方法,在其抛出Exception异常时执行  
  38.     //定义全局异常处理,value属性可以过滤拦截条件,此处拦截所有的Exception  
  39.     public String processUnauthenticatedException(NativeWebRequest request, Exception e) {    
  40.         return "error"//返回一个逻辑视图名    
  41.     }    
  42. }  

猜你喜欢

转载自blog.csdn.net/smile_lg/article/details/79708011