SpringMvc中框架价格ServletRequest对象以及处理方法的参数对象实例传递给DataBinder,DataBinder调用装配在Spring Web上下文中的ConversionService组件进行数据类型转换,数据格式化工作,并将ServletRequest中的消息填充到参数对象中,然后再调用Validator组件对已经绑定了请求消息数据的参数进行数据合法性校验,并最终生成数据绑定结果对象BindingResult。
Spring的转换器Converter的实现:
public class CustomerDateConverter implements Converter<String, Date>{
@Override
public Date convert(String source) {
try{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.parse(source);
}catch (Exception e) {
System.out.println(e.getMessage());
}
return null;
}
}
默认的情况下,<mvc:annotation-driven/>
会注册一个默认的ConversionService,即FormattingConversionServiceFactoryBean,以满足绝大多数类型转换的需求,但是现在需要自己定义一个ConversionService,所以需要进行一些配置
首先需要在Spring容器中注入自己定义的ConversionService
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<!-- 注意这里使用的应该是bean -->
<bean class="com.njust.ssm.controller.converter.CustomerDateConverter"></bean>
</set>
</property>
</bean>
- 使用
<mvc:annotation-driven/>
<mvc:annotation-driven conversion-service="conversionService" />
- 使用手动配置RequestMappingHandlerAdapter
<bean id="customerWebBinder"
class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="conversionService" ref="conversionService" />
</bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingInitializer" ref="customerWebBinder"></property>
</bean>
解释同上一篇SpringMvc的Validation