simpleTypeConverter
类型转换
SimpleTypeConverter typeConverter = new SimpleTypeConverter();
Integer number = typeConverter.convertIfNecessary("13",int.class);
System.out.println(number);
BeanWrapper
通过反射原理为bean赋值,走的是set方法;
DataBinder
数据绑定器
public static void main(String[] args) {
MyBean target = new MyBean();
DataBinder dataBinder = new DataBinder(target);
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("a","10");
pvs.add("b","hello");
dataBinder.bind(pvs);
System.out.println(target);
}
static class MyBean{
private int a;
private String b;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
@Override
public String toString() {
return "MyBean{" +
"a=" + a +
", b='" + b + '\'' +
'}';
}
}
DataBinder的扩展
可以通过ServletRequestDataBinderFactory 来对databinder进行扩展;
ConversionService
DefaultFormattingConversionService
// 默认conversionService
DefaultFormattingConversionService service = new DefaultFormattingConversionService();
ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
initializer.setConversionService(service);
// 用工厂创建DataBinder
ServletRequestDataBinderFactory factory = new ServletRequestDataBinderFactory(null,initializer);
WebDataBinder dataBinder = factory.createBinder(new ServletWebRequest(request), target, "user");
dataBinder.bind(new ServletRequestParameterPropertyValues(request));
绑定数据到指定的bean中时,如果是日期类型需要结合一个注解
代表当接收到了requet中参数类型是 yyyy|MM|dd时进行转换绑定到对应的属性上
@DateTimeFormat(pattern = "yyyy|MM|dd")
private Date a;
@InitBinder()
initBinder()也可以进行扩展;
优先采用initBinder的方法,再去找conversionService方法。