SpringMVC日期類型接收空值異常問題解決方法
最近遇到SpringMVC寫個(gè)controller類,傳一個(gè)空串的字符類型過來,正常情況是會(huì)自動(dòng)轉(zhuǎn)成date類型的,因?yàn)閿?shù)據(jù)表對(duì)應(yīng)類類型就是date的
解決方法是在controller類的后面加個(gè)注解:
@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ù)要傳個(gè)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來實(shí)現(xiàn),可以寫個(gè)簡單的例子,驗(yàn)證這個(gè)問題,DispatchInfoModel 類是我自己的測(cè)試類,里面有signDate這個(gè)date類型的參數(shù)
設(shè)置為true的情況,是可以正常運(yùn)行的
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的情況,會(huì)拋出異常:
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)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java數(shù)組隊(duì)列及環(huán)形數(shù)組隊(duì)列超詳細(xì)講解
隊(duì)列是一個(gè)有序列表,可以用數(shù)組和鏈表來實(shí)現(xiàn),隊(duì)列有一個(gè)原則。即:先存入隊(duì)列的數(shù)據(jù)要先取出,后存入的要后取出,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-09-09Java實(shí)現(xiàn)的并發(fā)任務(wù)處理實(shí)例
這篇文章主要介紹了Java實(shí)現(xiàn)的并發(fā)任務(wù)處理方法,結(jié)合實(shí)例形式較為詳細(xì)的分析了基于線程操作并發(fā)任務(wù)的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-11-11Java實(shí)現(xiàn)自動(dòng)獲取法定節(jié)假日詳細(xì)代碼
這篇文章主要給大家介紹了關(guān)于Java實(shí)現(xiàn)自動(dòng)獲取法定節(jié)假日的相關(guān)資料,獲取并處理節(jié)假日數(shù)據(jù)是一個(gè)常見需求,特別是在需要安排任務(wù)調(diào)度、假期通知等功能的場(chǎng)景中,需要的朋友可以參考下2024-05-05淺談HTTP使用BASIC認(rèn)證的原理及實(shí)現(xiàn)方法
下面小編就為大家?guī)硪黄獪\談HTTP使用BASIC認(rèn)證的原理及實(shí)現(xiàn)方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-11-11SpringCloud Bus如何實(shí)現(xiàn)配置刷新
這篇文章主要介紹了SpringCloud Bus如何實(shí)現(xiàn)配置刷新,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09