SpringMvc的转换器

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>
  1. 使用<mvc:annotation-driven/>
<mvc:annotation-driven conversion-service="conversionService" />
  1. 使用手动配置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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值