日常提交

This commit is contained in:
wu xiangkai
2022-12-19 20:34:16 +08:00
parent 3dec6613e8
commit 4016aa61e2

View File

@@ -499,3 +499,42 @@ public Account handle() {
return account; return account;
} }
``` ```
### DataBinder
对于@Controller和@ControllerAdvice类,在类中可以包含@InitBinder方法该方法用来初始化WebDataBinder实例
- 将请求参数绑定到model
- 将基于String类型的请求值例如请求参数pathVariableheaderscookies或其他转化为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