@ControllerAdvice三大功能
- 全局异常处理
- 全局数据绑定
- 全局数据预处理
全局异常处理
- @RestControllerAdvice ----- @RestController 返回字符串
- @ControllerAdvice ----- @Controller 返回视图
1.拦截所有异常,并把异常信息返回至浏览器页面上
spring.servlet.multipart.max-file-size=20KB
@RestControllerAdvice
public class MyGlobalException {
@ExceptionHandler(Exception.class)
public String customException(Exception e){
return e.getMessage();
}
}
2.拦截特定异常,并返回特定字符
添加其他异常:
@GetMapping("/errorTest")
public void erroTest(){
int i = 1/0;
}
特定异常处理:
@RestControllerAdvice
public class MyGlobalException {
@ExceptionHandler(MaxUploadSizeExceededException.class)
public String customException(MaxUploadSizeExceededException e){
return "文件大小超过限制";
}
}
@ExceptionHandler(ArithmeticException.class)
public String customException1(ArithmeticException e){
return "数学逻辑错误";
}
3.拦截异常,返回视图
定义视图:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>dong</h1>
<div th:text="${error}"></div>
</body>
</html>
拦截异常:
@ControllerAdvice
public class MyGlobalException {
@ExceptionHandler(MaxUploadSizeExceededException.class)
public ModelAndView customException(MaxUploadSizeExceededException e){
ModelAndView view = new ModelAndView("dong");
view.addObject("error",e.getMessage());
return view;
}
}
全局数据绑定
定义数据绑定类:
@ControllerAdvice
public class GetGlobalVeriables {
@ModelAttribute
public Map<String,String> getData(){
Map<String,String> info = new HashMap<>();
info.put("username","dong");
info.put("password","123");
return info;
}
}
定义测试类:
@RestController
public class HelloController {
@GetMapping("/hello")
public void getData(Model model){
Map<String, Object> asmap = model.asMap();
Map<String, String> map = (Map<String, String>) asmap.get("map");
Set<String> keySet = map.keySet();
for (String s : keySet) {
System.out.println(s+"-----"+map.get(s));
}
}
}
全局数据预处理
测试类:
Autor类:
public class Autor {
private String name;
private Integer age;
get和set方法...
}
book类:
public class Book {
private String name;
private Integer price;
get和set方法...
}
Controller:
@RestController
public class BookController {
@PostMapping("/book")
public void getbook(Book book,Autor autor){
System.out.println("book = " + book);
System.out.println("autor = " + autor);
}
}
Postman中Post请求:
结果并不理想:
我们发现两个类的属性并没有很好的区分
解决方法:
Controller类:
@RestController
public class BookController {
@PostMapping("/book")
public void getbook(@ModelAttribute("b") Book book, @ModelAttribute("a") Autor autor){
System.out.println("book = " + book);
System.out.println("autor = " + autor);
}
}
GetGlobalVeriables类:
@ControllerAdvice
public class GetGlobalVeriables {
@InitBinder("b")
public void bindMethod(WebDataBinder binder){
binder.setFieldDefaultPrefix("b.");
}
@InitBinder("a")
public void abindMethod(WebDataBinder binder){
binder.setFieldDefaultPrefix("a.");
}
}
Post请求:
结果正确: