Spring Boot2 系列(四) -@ControllerAdvice 的三种使用场景

顾名思义 就是 @Controller 的增强版
开门见山

  • 全局异常处理
  • 全局数据绑定
  • 全局数据预处理

全局异常处理

@ControllerAdvice
public class MyGlobalExceptionHandler {

    //全局异常处理
    @ExceptionHandler(ArrayIndexOutOfBoundsException.class)
    public ModelAndView customException(ArrayIndexOutOfBoundsException e){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("msg",e.getMessage());
        modelAndView.setViewName("myerror");
        return modelAndView;
    }
}

@ExceptionHandler 注解用来指明异常的处理类型

  • test
    @GetMapping("/hello")
    public String hello(){
        int[] a = new int[2];
        try {
            System.out.println(a[2]);
        }catch (ArrayIndexOutOfBoundsException e){
            throw new ArrayIndexOutOfBoundsException();
        }
        return "success";
    }

在这里插入图片描述

全局数据绑定

@ControllerAdvice
public class MyGlobalExceptionHandler {

    //全局数据绑定
    @ModelAttribute(name="data")
    public Map<String,String> myData(){
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("name","Mr-Jies");
        hashMap.put("age","20");
        return hashMap;
    }
}

@ModelAttribute 注解标记该方法的返回数据是一个全局数据,默认情况下,这个全局数据的 key 就是返回的变量名,value 就是方法返回值,当然开发者可以通过 @ModelAttribute 注解的 name 属性去重新指定 key。

  • test
    //全局数据绑定
    @ModelAttribute(name="data")
    public Map<String,String> myData(){
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("name","Mr-Jies");
        hashMap.put("age","20");
        return hashMap;
    }

在这里插入图片描述

全局数据预处理

@ControllerAdvice
public class MyGlobalExceptionHandler {

    //全局数据预处理
    @InitBinder("b")
    public void b(WebDataBinder binder){
        binder.setFieldDefaultPrefix("b.");
    }

    @InitBinder("a")
    public void a(WebDataBinder binder){
        binder.setFieldDefaultPrefix("a.");
    }
}

@InitBinder(“b”) 注解表示该方法用来处理和Book和相关的参数,在方法中,给参数添加一个 b 前缀,即请求参数要有b前缀.

  • test
    @PostMapping("/book")
    public String addBook2(@ModelAttribute("b") Book book, @ModelAttribute("a")Author author) {
        System.out.println(book);
        System.out.println(author);
        return "success";
    }

效果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值