在使用SpringMVC的時候,經(jīng)常會遇到表單中的日期字符串和JavaBean的Date類型的轉(zhuǎn)換,而SpringMVC默認(rèn)不支持這個格式的轉(zhuǎn)換,所以需要手動配置,自定義數(shù)據(jù)的綁定才能解決這個問題。
在需要日期轉(zhuǎn)換的Controller中使用SpringMVC的注解@initbinder和Spring自帶的WebDateBinder類來操作。
WebDataBinder是用來綁定請求參數(shù)到指定的屬性編輯器.由于前臺傳到controller里的值是String類型的,當(dāng)往Model里Set這個值的時候,如果set的這個屬性是個對象,Spring就會去找到對應(yīng)的editor進(jìn)行轉(zhuǎn)換,然后再SET進(jìn)去。
代碼如下:
1
2
3
4
5
6
|
@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的配置文件加上
1
2
3
4
5
6
7
8
9
10
|
<!-- 解析器注冊 --> < 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" /> |
換種寫法
1
2
3
4
5
6
7
|
< 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自己提供了大量的實(shí)現(xiàn)類,諸如CustomDateEditor ,CustomBooleanEditor,CustomNumberEditor等許多,基本上夠用。
使用時候調(diào)用WebDataBinder的registerCustomEditor方法
registerCustomEditor源碼:
1
2
3
|
public void registerCustomEditor(Class<?> requiredType, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, propertyEditor); } |
第一個參數(shù)requiredType是需要轉(zhuǎn)化的類型。
第二個參數(shù)PropertyEditor是屬性編輯器,它是個接口,以上提到的如CustomDateEditor等都是繼承了實(shí)現(xiàn)了這個接口的PropertyEditorSupport類。
我們也可以不使用他們自帶的這些編輯器類。
我們可以自己構(gòu)造:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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(); } } |
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.cnblogs.com/aheizi/p/5440884.html