@ControllerAdvice就是@Controller的增强版。
@ControllerAdvice主要用来处理全局数据,一般搭配@ExceptionHandler、@ModelAttribute以及@InitBinder使用。
- 全局异常处理
通过@ControllerAdvice结合@ExceptionHandler定义全局异常捕获机制
// 在类名上加上@ControllerAdvice注解
@ControllerAdvice
public class CustomerExceptionHandler {
//表明该方法用来处理MaxUploadSizeExceededException类型的异常
@ExceptionHandler(MaxUploadSizeExceededException.class)
public ModelAndView uploadExceptionRT(MaxUploadSizeExceededException e) throws IOException {
ModelAndView view = new ModelAndView();
view.addObject("msg","文件上传大小超过限制");
view.setViewName("error");
return view;
}
}
- 设置全局数据
在@ControllerAdvice中配置全局数据,使用@ModelAttribute注解进行配置
//将这个方法的返回值信息存放进strInfo中
// 也可以换成其他的数据类型和数据,例如对象,map等等,只是遍历的方式需要改变
@ModelAttribute(value = "strInfo")
public String strInfo(){
return "全局数据";
}
// 可以在请求方法中通过Model获取
@GetMapping("/strInfo")
public String getStrInfo(Model model){
return model.getAttribute("strInfo").toString();
}
-
请求参数预处理
@ControllerAdvice结合@InitBinder还能实现请求参数预处理,即将表单中的数据绑定到实体类上时进行一些额外处理,可以避免参数同名时的冲突,例如注意:不要将装订名binder和请求参数的前缀名prefix混淆,
// 在打了ControllerAdvice注解的类中定义如下
/**
* @InitBinder("a")表示该方法是处理@ModelAttribute("a")对应的参数的,为了在每个方法中给相应的Field设置一个前缀
* 例如au,相当于获取传过来的au.name等等参数
* 在WebDataBinder对象中,还可以设置允许的字段、禁止的字段、必填字段以及验证器
*/
@InitBinder("a")
public void inita(WebDataBinder binder) {
binder.setFieldDefaultPrefix("au.");
}
@InitBinder("b")
public void initb(WebDataBinder binder) {
binder.setFieldDefaultPrefix("bk.");
}
//这时,我获取请求时对应前缀所传输的值,应为?bk.name=三国演义&bk.author=罗贯中&au.name=曹雪芹&au.age=33就可以正确赋给对应的值
//不过直接传输name的方式还能使用,所以传输参数时要注意
@GetMapping("/book")
public String book(@ModelAttribute("a") Author author,@ModelAttribute("b") Book book){
System.out.println(author.getName()+"--------"+book.getName());
return book.toString()+">>>>>>>>>>>"+author.toString();
}