SpringMVC数据绑定
前言:由于请求中所带来的数据参数都是以key,value形式传递到controller,而传递过来的数据类型都是为String,当我们需要Integer,Date,Double等非String数据时,我们需要对其进行转换成需要的数据类型。
请求数据到controller过程:
1.绑定简单类型
String---》Integer,Double,Float等数据类型,只要参数名字一致就可以绑定。
2.绑定简单的pojo类型
简单pojo类型只包括简单类型的属性。
绑定过程:request请求的参数名称和pojo的属性名一致,就可以绑定成功。
缺点:多个pojo拥有相同的属性名称。例,用户(user),员工(employee)都拥有name属性,在绑定的时候会导致无法绑定。
3.绑定包装的pojo类型
在页面的时候,指定所绑定的对象,例如user.name,employee.name
4.属性编辑器(propertyEditor)(了解)
SpringMVC没有支持全部的属性转换,所以需要我们自己自定义。
//自定义属性编辑器
@InitBinder
public void initBinder(WebDataBinder binder) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class,
new CustomDateEditor(sdf, true));
}
缺点:只能作用于当前页面,无法进行多个controller共用。
所以有了下面一种,
public class CustomPropertyEditor implements PropertyEditorRegistrar
{
@Override
public void registerCustomEditors(PropertyEditorRegistry binder) {
binder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
}
}
<!-- 注册属性编辑器 -->
<bean id="customPropertyEditor" class="cn.itcast.ssm.propertyeditor.CustomPropertyEditor"></bean>
<!-- 自定义webBinder -->
<bean id="customBinder"
class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="propertyEditorRegistrars">
<list>
<ref bean="customPropertyEditor"/>
</list>
</property>
</bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingInitializer" ref="customBinder"></property>
</bean>
5.转换器(converter)
定义一个转换器并注册,加入适配器中
public class CustomDateConverter implements Converter<String, Date>{
@Override
public Date convert(String source) {
try {
return new SimpleDateFormat("yyyy-MM-dd").parse(source);
} catch (ParseException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
return null;
}
}
springmvc.xml配置
<mvc:annotation-driven conversion-service="conversionService" />
<!--转换器-->
<!-- conversionService -->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="conver.CustomDateConverter"/>
</set>
</property>
</bean>
配好之后,Date类型的数据需要,就会自动转换了。