SpringMVC日期類型接收空值異常問題解決方法
最近遇到SpringMVC寫個controller類,傳一個空串的字符類型過來,正常情況是會自動轉(zhuǎn)成date類型的,因為數(shù)據(jù)表對應(yīng)類類型就是date的
解決方法是在controller類的后面加個注解:
@InitBinder
protected void initDateFormatBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
注意,上面的代碼CustomDateEditor構(gòu)造函數(shù)要傳個true參數(shù),表示允許傳空字符串來進(jìn)行日期類型轉(zhuǎn)換
CustomDateEditor 里源碼
public class CustomDateEditor extends PropertyEditorSupport {
private final DateFormat dateFormat;
private final boolean allowEmpty;
private final int exactDateLength;
public CustomDateEditor(DateFormat dateFormat, boolean allowEmpty) {
this.dateFormat = dateFormat;
this.allowEmpty = allowEmpty;
this.exactDateLength = -1;
}
....
}
Spring Bean類的裝載是通過BeanWrapperImpl來實現(xiàn),可以寫個簡單的例子,驗證這個問題,DispatchInfoModel 類是我自己的測試類,里面有signDate這個date類型的參數(shù)
設(shè)置為true的情況,是可以正常運行的
public class mytest {
public static void main(String[] args) {
DispatchInfoModel tm = new DispatchInfoModel();
BeanWrapper bw = new BeanWrapperImpl(tm);
bw.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
bw.setPropertyValue("signDate", "");
System.out.println(tm.getSignDate());
}
}
設(shè)置為false的情況,會拋出異常:
public class mytest {
public static void main(String[] args) {
DispatchInfoModel tm = new DispatchInfoModel();
BeanWrapper bw = new BeanWrapperImpl(tm);
bw.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false));
bw.setPropertyValue("signDate", "");
System.out.println(tm.getSignDate());
}
}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java中對list map根據(jù)map某個key值進(jìn)行排序的方法
今天小編就為大家分享一篇Java中對list map根據(jù)map某個key值進(jìn)行排序的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07
Java實現(xiàn)紀(jì)元秒和本地日期時間互換的方法【經(jīng)典實例】
這篇文章主要介紹了Java實現(xiàn)紀(jì)元秒和本地日期時間互換的方法,結(jié)合具體實例形式分析了Java日期時間相關(guān)操作技巧,需要的朋友可以參考下2017-04-04
mybatis學(xué)習(xí)筆記之mybatis注解配置詳解
本篇文章主要介紹了mybatis學(xué)習(xí)筆記之mybatis注解配置詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-12-12
SpringBoot實現(xiàn)WebSocket即時通訊的示例代碼
本文主要介紹了SpringBoot實現(xiàn)WebSocket即時通訊的示例代碼,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-04-04
spring @Profiles和@PropertySource實現(xiàn)根據(jù)環(huán)境切換配置文件
這篇文章主要介紹了spring @Profiles和@PropertySource根據(jù)環(huán)境切換配置文件,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11
Java中ThreadLocal線程變量的實現(xiàn)原理
本文主要介紹了Java中ThreadLocal線程變量的實現(xiàn)原理,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06

