zoukankan      html  css  js  c++  java
  • SpringBoot整合WEB开发--(四)@ControllerAdvice

    1.全局异常处理

    @ControllerAdvice处理全局数据,一般搭配@ExceptionHandler,@ModelAttribute以及@InitBinder使用。
    @ControllerAdvice
    public class CustomExceptionHandler {
        @ExceptionHandler(MaxUploadSizeExceededException.class)
        public ModelAndView uploadException(MaxUploadSizeExceededException e) throws IOException {
            ModelAndView mv = new ModelAndView();
            mv.addObject("msg", "上传文件大小超出限制!");
            mv.setViewName("error");
            return mv;
        }
    
        @ExceptionHandler(Exception.class)
        public void myexce(Exception e) {
            System.out.println("myexce>>>"+e.getMessage());
        }
    }

    2.添加全局数据

      @ModelAttribute配置全局数据,如下:key="info",value="map",

    @ControllerAdvice
    public class GlobalConfig {
        @ModelAttribute(value = "info")
        public Map<String,String> userInfo() {
            HashMap<String, String> map = new HashMap<>();
            map.put("username", "罗贯中");
            map.put("gender", "男");
            return map;
        }
    }

    controller:

     @GetMapping("/hello")
        @ResponseBody
        public void hello(Model model) {
            Map<String, Object> map = model.asMap();                //获取到全局数据key="info",value="map"
            Set<String> keySet = map.keySet();
            Iterator<String> iterator = keySet.iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                Object value = map.get(key);
                System.out.println(key + ">>>>>" + value);
            }
        }

    http://localhost:8080/hello

    3.请求参数预处理

    @ControllerAdvice结合@InitBinder可以实现请求参数预处理,即将表单中的数据绑定到实体类上时进行一些额外的处理。

    问题:两个实体类,属性名字一致,传递参数时参数无法指定具体的一个,如下,两个实体类都有name属性,url拼接时出现问题。


    demo:
    实体类:
    public class Author {
        private String name;
        private int age;
        。。。。。。。。
    }
    public class Book {
        private String name;
        private String author;
    。。。。。。。。。。
    }
    @ControllerAdvice
    public class GlobalConfig {
      @InitBinder("b")
    public void init(WebDataBinder binder) {
    binder.setFieldDefaultPrefix("b."); //处理@ModelAttribute("b")的参数
        }
    @InitBinder("a")
    public void init2(WebDataBinder binder) {
    binder.setFieldDefaultPrefix("a.");         //处理@ModelAttribute("a")的参数
        }
    }

    controller:

    @GetMapping("/book")
        @ResponseBody
        public String book(@ModelAttribute("b") Book book, @ModelAttribute("a") Author author) {
            return book.toString() + ">>>" + author.toString();
        }



  • 相关阅读:
    【C++ Primer Chapter 3 总结】Library vector & string Type
    【C++ Primer Chapter 4 总结】左值 & 右值
    【C++ Primer Chapter 6 总结】函数
    mysql添加索引
    注册plsql
    挑战答题小程序
    开源答题小程序
    答题如何防止作弊
    党史知识答题活动小程序复盘整理
    党史学习教育答题活动复盘
  • 原文地址:https://www.cnblogs.com/crazy-lc/p/12317249.html
Copyright © 2011-2022 走看看