簡體   English   中英

Spring MVC對象時間戳綁定中的字段錯誤

[英]spring mvc Field error in object timestamp binding

我正在使用Spring 4.1.7.RELEASE。

我不能將date元素綁定到bean屬性。

我嘗試創建一個全局活頁夾。

我不知道我在做什么錯。

@ControllerAdvice
public class CommonBindingInitializer {
    private static final String DATE_FORMAT = "yyyy-MM-dd";
    @InitBinder
    public void registerCustomEditors(WebDataBinder binder, WebRequest request) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, request.getLocale());
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, null, new CustomDateEditor(dateFormat, true));
        binder.registerCustomEditor(java.util.Date.class, null, new CustomDateEditor(dateFormat, true));
        binder.registerCustomEditor(Timestamp.class, null, new CustomDateEditor(dateFormat, true));
    }
}

但這不能解決我的問題。在我的控制器中,我總是有錯誤:

org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'searchCriteria' on field 'dateCreation': rejected value [2015-09-16]; 
codes [typeMismatch.searchCriteria.dateCreation,typeMismatch.dateCreation,typeMismatch.java.sql.Timestamp,typeMismatch]; 
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [searchCriteria.dateCreation,dateCreation]; arguments []; 
default message [dateCreation]]; 
default message [Failed to convert property value of type 'java.lang.String' to required type 'java.sql.Timestamp' for property 'dateCreation'; 
nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [java.lang.String] to required type [java.sql.Timestamp] 
for property 'dateCreation': 
PropertyEditor [org.springframework.beans.propertyeditors.CustomDateEditor] returned inappropriate value of type [java.util.Date]]

你能告訴我怎么了嗎?

謝謝。

尋找解決方案。

就像Ralph在此評論中所說的, Timestamp Spring轉換非常清楚。

CustomDateEditor將字符串轉換為java.util.Date(而不是java.sql.Timestamp)。

我通過覆蓋CustomDateEditor並實例化了一個新的Timestamp而不是setAsText方法中的java.util.date來完成自己的屬性編輯器類。 而且效果很好。

希望它能幫助某人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM