在實際操作中經常會碰到表單中的日期 字符串和Javabean中的日期類型的屬性自動轉換, 而springMVC默認不支持這個格式的轉換,所以必須要手動配置, 自定義數據類型的綁定才能實現這個功能。
一、控制器中代碼
比較簡單的可以直接應用springMVC的注解@initbinder和spring自帶的WebDataBinder類和操作,controller中配置了initBinder()時則再接收String型的日期時會自動轉換。
package com.shiliu.game.controller; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; public class InitController { /** * 自動轉換日期類型的字段格式 */ @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, 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"> <property name="supportedMediaTypes"> <list> <value>text/html; charset=utf-8</value> </list> </property> </bean>
此篇內容參考:http://blog.csdn.net/jiubugeinifo/article/details/41678717