在使用SpringMVC的時候,經常會遇到表單中的日期字符和JavaBean 的 Date類型的轉換,而SpringMVC默認不支持這個轉換,所以需要手動設置,自定義數據的綁定才能解決這個問題。
在需要日期轉換的Controller中使用SpringMVC的註解@initbinder和Spring自帶的WebDateBinder類來操作。
WebDateBinder 是用來綁定請求參數到指定的屬性編輯器.由於前臺傳到controller 裏的值是String類型的,當往Model中Set這個值的時候,如果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 ,CustomBooleanEditor,CustomNumberEditor等許多,基本上夠用。
使用時候調用WebDataBinder的registerCustomEditor方法
registerCustomEditor源碼:
public void registerCustomEditor(Class<?>requiredType, PropertyEditor propertyEditor) {
getPropertyEditorRegistry().registerCustomEditor(requiredType,propertyEditor);
}
第一個參數requiredType是需要轉化的類型。
第二個參數PropertyEditor是屬性編輯器,它是個接口,以上提到的如CustomDateEditor等都是繼承了實現了這個接口的PropertyEditorSupport類。
我們也可以不使用他們自帶的這些編輯器類。