【问题标题】:spring mvc Field error in object timestamp binding对象时间戳绑定中的spring mvc字段错误
【发布时间】:2015-09-27 08:46:59
【问题描述】:

我正在使用 spring 4.1.7.RELEASE。

我无法将日期元素绑定到 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]]

你能告诉我有什么问题吗?

谢谢。

【问题讨论】:

    标签: java spring spring-mvc binding timestamp


    【解决方案1】:

    找到解决方案。

    正如 Ralph 在此评论中所说的 Timestamp Spring conversion 非常清楚。

    CustomDateEditor 将字符串转换为 java.util.Date(而不是 java.sql.Timestamp)。

    我通过重写 CustomDateEditor 并在 setAsText 方法中实例化一个新的 Timestamp 而不是 java.util.date 来完成我自己的属性编辑器类。它工作正常。

    希望对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 2011-04-11
      • 2013-01-17
      • 2014-05-08
      • 1970-01-01
      • 2012-04-25
      • 1970-01-01
      • 1970-01-01
      • 2012-02-20
      • 2011-10-23
      相关资源
      最近更新 更多