Springmvc注解@initbinder解决类型转换问题

在使用SpringMVC的时候,经常会遇到表单中的日期字符和JavaBean Date类型的转换,而SpringMVC默认不支持这个转换,所以需要手动设置,自定义数据的绑定才能解决这个问题。

在需要日期转换的Controller中使用SpringMVC的注解@initbinderSpring自带的WebDateBinder类来操作。

 

WebDateBinder 是用来绑定请求参数到指定的属性编辑器.由于前台传到controller 里的值是String类型的,当往ModelSet这个值的时候,如果set的这个属性是个对象,Spring就会去找到对应的editor进行转换,然后在SET进去。

代码如下:


	@InitBinder  
public void initBinder(WebDataBinder binder) {  
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
    dateFormat.setLenient(false);  
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));  
}



需要在 SpringMVC 的配置文件加上

	<!-- 解析器注册 -->  
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">  
    <property name="messageConverters">  
        <list>  
            <ref bean="stringHttpMessageConverter"/>  
        </list>  
    </property>  
</bean>  
<!-- String类型解析器,允许直接返回String类型的消息 -->  
<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter"/> 

换种写法


	<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <constructor-arg value="UTF-8"/>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

拓展:

spring mvc在绑定表单之前,都会先注册这些编辑器,Spring自己提供了大量的实现类,诸如CustomDateEditor CustomBooleanEditorCustomNumberEditor等许多,基本上够用。

使用时候调用WebDataBinderregisterCustomEditor方法

registerCustomEditor源码:

public void registerCustomEditor(Class<?>requiredType, PropertyEditor propertyEditor) {
   getPropertyEditorRegistry().registerCustomEditor(requiredType,propertyEditor);
}

第一个参数requiredType是需要转化的类型。

第二个参数PropertyEditor是属性编辑器,它是个接口,以上提到的如CustomDateEditor等都是继承了实现了这个接口的PropertyEditorSupport类。

我们也可以不使用他们自带的这些编辑器类。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值