diff --git a/spring/Spring core/SpringMVC.md b/spring/Spring core/SpringMVC.md index 537b29a..01394e5 100644 --- a/spring/Spring core/SpringMVC.md +++ b/spring/Spring core/SpringMVC.md @@ -499,3 +499,42 @@ public Account handle() { return account; } ``` +### DataBinder +对于@Controller和@ControllerAdvice类,在类中可以包含@InitBinder方法,该方法用来初始化WebDataBinder实例: +- 将请求参数绑定到model +- 将基于String类型的请求值(例如请求参数,pathVariable,headers,cookies或其他)转化为controller method参数的类型 +- 在html渲染时,将model object value转化为String的形式 + +@InitBinder可以针对特定的Controller注册java.beans.PropertyEditor或Spring Converter和Formatter 组件。 +@InitBinder支持和@RequestMapping方法一样的参数形式,但是参数不能使用@ModelAttribute注解。通常,@InitBinder方法的参数为WebDataBinder,且返回类型为void: +```java +@Controller +public class FormController { + // WebDataBinder参数用于注册 + @InitBinder + public void initBinder(WebDataBinder binder) { + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); + dateFormat.setLenient(false); + binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); + } + + // ... +} +``` +同样,当使用一个共享的FormattingConversionService来设置格式时,可以注册针对特定Controller的Formatter实现,例如: +```java +@Controller +public class FormController { + + @InitBinder + protected void initBinder(WebDataBinder binder) { + binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd")); + } + + // ... +} +``` +### Model Design +在web应用的上下文中,data binding涉及将http请求中的参数绑定到model object及其内层嵌套对象中。 +默认情况下,所有spring允许绑到model object中所有的公共属性(有public的getter和setter)。 +