转载自:
https://blog.csdn.net/ai_xiangjuan/article/details/79842385
https://blog.csdn.net/ai_xiangjuan/article/details/79696639
@InitBinder用于在@Controller中标注于方法上,表示为当前控制器注册一个属性编辑器,只对当前的Controller有效。@InitBinder标注的方法必须有一个参数WebDataBinder。所谓的属性编辑器可以理解就是帮助我们完成参数绑定。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @ResponseBody @RequestMapping(value = "/test") public String test(@RequestParam String name,@RequestParam Date date) throws Exception { System.out.println(name); System.out.println(date); return name; }
@InitBinder public void initBinder(WebDataBinder binder){ binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));
}
|
上面例子中,@InitBinder方法会帮助我们把String类型的参数先trim再绑定,而对于Date类型的参数会先格式化在绑定。例如当请求是/test?name=%20zero%20&date=2018-05-22时,会把zero绑定到name,再把时间串格式化为Date类型,再绑定到date。
这里的@InitBinder方法只对当前Controller生效,要想全局生效,可以使用@ControllerAdvice。通过@ControllerAdvice可以将对于控制器的全局配置放置在同一个位置,注解了@ControllerAdvice的类的方法可以使用@ExceptionHandler,@InitBinder,@ModelAttribute注解到方法上,这对所有注解了@RequestMapping的控制器内的方法有效。
1 2 3 4 5 6 7 8 9 10 11 12 13
| @ControllerAdvice public class GlobalControllerAdvice {
@InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));
} }
|
除了使用@ControllerAdvice来配置全局的WebDataBinder,还可以使用RequestMappingHandlerAdapter:
1 2 3 4 5 6 7 8 9 10 11 12 13
| @Bean public RequestMappingHandlerAdapter webBindingInitializer() { RequestMappingHandlerAdapter adapter = new RequestMappingHandlerAdapter(); adapter.setWebBindingInitializer(new WebBindingInitializer(){
@Override public void initBinder(WebDataBinder binder, WebRequest request) { binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));
} }); return adapter; }
|
如上示例,可以实现同样的效果。
@ControllerAdvice中除了配置@InitBinder,还可以有@ExceptionHandler用于全局处理控制器里面的异常;@ModelAttribute作用是绑定键值对到Model里,让全局的@RequestMapping都能获得在此处设置的键值对。
补充:如果 @ExceptionHandler 注解中未声明要处理的异常类型,则默认为方法参数列表中的异常类型。示例:
1 2 3 4 5 6 7 8 9
| @ControllerAdvice public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class) @ResponseBody String handleException(Exception e){ return "Exception Deal! " + e.getMessage(); } }
|