1. 程式人生 > >Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'xxx'

Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'xxx'

今天在完成專案的時候遇到了下面的異常資訊:

04-Aug-2014 15:49:27.894 SEVERE [http-apr-8080-exec-5] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [cms] in context with path [/cms] threw exception [Request processing failed; nested exception is org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 6
errors Field error in object 'carContractSearchBox' on field 'createEndDate': rejected value []; codes [typeMismatch.carContractSearchBox.createEndDate,typeMismatch.createEndDate,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [carContractSearchBox.createEndDate,createEndDate]; arguments []; default
message [createEndDate]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'createEndDate'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for
property 'createEndDate': no matching editors or conversion strategy found]

先說明一下,我們的專案使用的是Spring MVC。相應的功能是一個簡單的form表單查詢功能,裡面有一些日期欄位的查詢。

相應的解決辦法為:

在對應的controller中增加屬性編輯器:

@InitBinder
protected void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}

注意這塊的new CustomDateEditor(dateFormat, true)中的true,檢視CustomDateEditor原始碼可以看到:

/**
 * Create a new CustomDateEditor instance, using the given DateFormat
 * for parsing and rendering.
 * <p>The "allowEmpty" parameter states if an empty String should
 * be allowed for parsing, i.e. get interpreted as null value.
 * Otherwise, an IllegalArgumentException gets thrown in that case.
 * @param dateFormat DateFormat to use for parsing and rendering
 * @param allowEmpty if empty strings should be allowed
 */
public CustomDateEditor(DateFormat dateFormat, boolean allowEmpty) {
    this.dateFormat = dateFormat;
    this.allowEmpty = allowEmpty;
    this.exactDateLength = -1;
}

allowEmpty欄位為true的時候form表單傳遞的值可以為空。否則會出現""字串解析為date報錯。