@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();
}
}
@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 "数学逻辑错误";
}
<!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.");
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/15762.html