学习@ControllerAdvice注解

@ControllerAdvice的三大用法
1.处理全局异常
2.预设全局数据
3.请求参数预处理

一:处理全局异常

@ControllerAdvice
public class MyCustomException {
//这个注解指定拦截异常的大小
@ExceptionHandler(MaxUploadSizeExceededException.class)
@ExceptionHandler(MaxUploadSizeExceededException.class)
public ModelAndView myexception(MaxUploadSizeExceededException e) throws IOException {
ModelAndView error=new ModelAndView(“error”);
error.addObject(“error”,“上传文件过大”);
return error;
}
}

二:预设全局数据

/**

  • 这个类里面的数据在工程中任何一个controller都能取到
    */
    @ControllerAdvice
    public class GlobalData {
    @ModelAttribute(value = “info”)
    public Map mydata(){
    Map map=new HashMap<>();
    map.put(“name”,“hhh”);
    map.put(“address”,“xxxx”);
    return map;
    }
    }

三.请求参数预处理

@RestController
public class BookController {
@PostMapping("/book")
public void addBook(@ModelAttribute(“b”) Book book, @ModelAttribute(“a”) Author author){
System.out.println(book);
System.out.println(author);
}
@InitBinder(“a”)
public void InitA(WebDataBinder binder){
binder.setFieldDefaultPrefix(“a.”);
}
@InitBinder(“b”)
public void InitB(WebDataBinder binder){
binder.setFieldDefaultPrefix(“b.”);
}
}

`

你可能感兴趣的:(学习@ControllerAdvice注解)