SpringMVC注解@initbinder解決類型轉換問題


在使用SpringMVC的時候,經常會遇到表單中的日期字符串和JavaBean的Date類型的轉換,而SpringMVC默認不支持這個格式的轉換,所以需要手動配置,自定義數據的綁定才能解決這個問題。
在需要日期轉換的Controller中使用SpringMVC的注解@initbinder和Spring自帶的WebDateBinder類來操作。
WebDataBinder是用來綁定請求參數到指定的屬性編輯器.由於前台傳到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類。
我們也可以不使用他們自帶的這些編輯器類。
我們可以自己構造:

import org.springframework.beans.propertyeditors.PropertiesEditor; public class DoubleEditor extends PropertyEditorSupport { @Override public void setAsText(String text) throws IllegalArgumentException { if (text == null || text.equals("")) { text = "0"; } setValue(Double.parseDouble(text)); } @Override public String getAsText() { return getValue().toString(); } }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM