zoukankan      html  css  js  c++  java
  • @RestControllerAdvice

    在spring 3.2中,新增了@ControllerAdvice 注解,可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute,并应用到所有@RequestMapping中。

    @ControllerAdvice
    public class MyControllerAdvice {
    
        /**
         * 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器
         * @param binder
         */
        @InitBinder
        public void initBinder(WebDataBinder binder) {}
    
        /**
         * 把值绑定到Model中,使全局@RequestMapping可以获取到该值
         * @param model
         */
        @ModelAttribute
        public void addAttributes(Model model) {
            model.addAttribute("author", "Magical Sam");
        }

        /**
         * 全局异常捕捉处理
         * @param ex
         * @return
         */
        @ResponseBody
        @ExceptionHandler(value = Exception.class)
        public Map errorHandler(Exception ex) {
            Map map = new HashMap();
            map.put("code", 100);
            map.put("msg", ex.getMessage());
            return map;
        }
    }
    @ModelAttribute:在Model上设置的值,对于所有被 @RequestMapping 注解的方法中,都可以通过 ModelMap 获取,如下:



    @RequestMapping(
    "/home") public String home(ModelMap modelMap) { System.out.println(modelMap.get("author")); } //或者 通过@ModelAttribute获取 @RequestMapping("/home") public String home(@ModelAttribute("author") String author) { System.out.println(author); }
  • 相关阅读:
    LeetCode题解No11——“盛水最多的容器”
    第二次作业
    第一章 模式识别基本概念
    第一次个人作业
    第02组 Beta版本演示
    第02组 Beta冲刺(4/4)
    第02组 Beta冲刺(3/4)
    第02组 Beta冲刺(2/4)
    第02组 Beta冲刺(1/4)
    第02组 Alpha事后诸葛亮
  • 原文地址:https://www.cnblogs.com/qq376324789/p/13753078.html
Copyright © 2011-2022 走看看