最近遇到SpringMVC寫個controller類,傳一個空串的字元類型過來,正常情況是會自動轉成date類型的,因為資料表對應類類型就是date的
解決方法是在controller類的後面加個注解:
@InitBinder
protected void initDateFormatBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
注意,上面的代碼CustomDateEditor構造函數要傳個true參數,表示允許傳空字元串來進行日期類型轉換
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來實作,可以寫個簡單的例子,驗證這個問題,DispatchInfoModel 類是我自己的測試類,裡面有signDate這個date類型的參數
設定為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());
}
}
設定為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());
}
}

以上就是本文的全部内容,希望對大家的學習有所幫助,也希望大家多多支援腳本之家。