springMVC注解@initbinder

在实际操作中经常会碰到表单中的日期 字符串和Javabean中的日期类型的属性自动转换, 而springMVC默认不支持这个格式的转换,所以必须要手动配置, 自定义数据类型的绑定才能实现这个功能。

比较简单的可以直接应用springMVC的注解@initbinder和spring自带的WebDataBinder类和操作

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. @InitBinder  
  2.     public void initBinder(WebDataBinder binder) {  
  3.         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
  4.         dateFormat.setLenient(false);  
  5.         binder.registerCustomEditor(Date.classnew CustomDateEditor(dateFormat, true));  
  6.     }  
还要在springMVC配置文件中加上

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <!-- 解析器注册 -->  
  2.     <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">  
  3.         <property name="messageConverters">  
  4.             <list>  
  5.                 <ref bean="stringHttpMessageConverter"/>  
  6.             </list>  
  7.         </property>  
  8.     </bean>  
  9.     <!-- String类型解析器,允许直接返回String类型的消息 -->  
  10.     <bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter"/>  
这样就可以直接将上传的日期时间字符串绑定为日期类型的数据了
原文地址:https://www.cnblogs.com/hzcya1995/p/13317761.html