@ControllerAdvice的三大应用场景
@ControllerAdvice接口在Spring项目中有三个应用场景,分别如下
1、全局异常处理
2、全局数据绑定
3、全局数据预处理
下面将简单介绍这三种用法及其使用场景
1、全局异常处理
在SpringMVC应用中,通常需要对所有的控制器方法做统一的异常处理。在服务器程序发生异常的情况下,返回友好的提示信息给客户端。
使用@ContrllerAdvice+@ExceptionHandler可以实现全局异常处理功能。被处理的异常类型,可以在@ExceptionHandler的value属性指定。
配置代码如下
@ControllerAdvice
public class MyControllerAdvice {
//全局异常处理
@ExceptionHandler(Exception.class)
@ResponseBody
public Map<String,Object> handleException(){
Map<String,Object> map = new HashMap<>();
map.put("msg","服务器发生错误");
return map;
}
}
2、全局数据绑定
在某些场景下,需要在控制器方法中获取一些通用的数据,比如系统配置。
使用@ControllerAdvice+@ModelAttribute可以实现将属性注入到所有接口的Model中。
全局数据绑定配置如下:
@ControllerAdvice
public class MyControllerAdvice {
//全局数据绑定
@ModelAttribute
public Map<String,Object> addModel(){
Map<String,Object> map = new HashMap<>();
map.put("id",1);
map.put("city","揭阳");
return map;
}
}
在控制器方法中获取全局绑定的数据
//测试全局数据绑定接口
@GetMapping("/test2")
public Map<String,Object> test2(Model model){
Map<String, Object> map = model.asMap();
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.println(entry.getKey()+":"+entry.getValue());
}
return map;
}
3、全局数据预处理
在编写SpringMVC接口时,有时候会出现接受数据的实体类中含有相同的参数,导致不同的实体对象中相同参数名的属性接收到的数据是相同的。
比如,接口方法输入一个User类型的参数和一个Person类型的参数,User类和Person类中都有name属性,将会导致两个对象的name属性接受到的值是相同的。
全局数据预处理的配置如下:
@ControllerAdvice
public class MyControllerAdvice {
//全局数据预处理
@InitBinder("p")
public void p(WebDataBinder binder){
binder.setFieldDefaultPrefix("p.");
}
@InitBinder("u")
public void u(WebDataBinder binder){
binder.setFieldDefaultPrefix("u.");
}
}
接口方法编写如下:
//测试全局数据预处理接口
@GetMapping("/test3")
public Map<String,Object> test3(@ModelAttribute("u") User user, @ModelAttribute("p") Person person){
Map<String,Object> map = new HashMap<>();
map.put("success",true);
System.out.println(user);
System.out.println(person);
return map;
}
浏览器访问测试全局数据预处理接口
http://localhost:8080/test3?p.name=123&p.age=12&u.name=cxj&u.age=22
查看获取结果