Spring @ControllerAdvice 注解

  1. 通过@ControllerAdvice注解可以将对于控制器的全局配置放在同一个位置。
  2. 注解了@Controller的类的方法可以使用@ExceptionHandler、@InitBinder、@ModelAttribute注解到方法上。
  3. @ControllerAdvice注解将作用在所有注解了@RequestMapping的控制器的方法上
  4. @ExceptionHandler:用于全局处理控制器里的异常。
  5. @InitBinder:用来设置WebDataBinder,用于自动绑定前台请求参数到Model中。
  6. @ModelAttribute:本来作用是绑定键值对到Model中,此处让全局的@RequestMapping都能获得在此处设置的键值对。
  7. import org.springframework.ui.Model;
    import org.springframework.web.bind.WebDataBinder;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.InitBinder;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.context.request.WebRequest;
    import org.springframework.web.servlet.ModelAndView;
    
    /**
     * @author Kevin
     * @description
     * @date 2016/7/4
     */
    @ControllerAdvice
    public class DemoHandlerAdvice {
        // 定义全局异常处理,value属性可以过滤拦截条件,此处拦截所有的Exception
        @ExceptionHandler(value = Exception.class)
        public ModelAndView exception(Exception exception, WebRequest request) {
            ModelAndView mv = new ModelAndView("error");
            mv.addObject("errorMessage", exception.getMessage());
            return mv;
        }
    
        // 此处将键值对添加到全局,注解了@RequestMapping的方法都可以获得此键值对
        @ModelAttribute
        public void addAttributes(Model model){
            model.addAttribute("msg","额外的信息");
        }
    
        // 此处仅演示忽略request中的参数id
        @InitBinder
        public void initBinder(WebDataBinder webDataBinder){
            webDataBinder.setDisallowedFields("id");
        }
    }
    

    控制器

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    /**
     * @author Kevin
     * @description
     * @date 2016/7/4
     */
    @Controller
    public class DemoController {
        
        @RequestMapping("/advice")
        public String advice(@ModelAttribute("msg") String msg) throws Exception {
            throw new Exception("参数错误" + msg);
        }
    }

    控制器中抛出的异常将被自定义全局异常捕获,并返回至error页面。


你可能感兴趣的:(Java)