java - spring mvc 对象时间戳绑定(bind)中的字段错误

标签 java spring spring-mvc binding timestamp

我正在使用 spring 4.1.7.RELEASE。

我无法将日期元素绑定(bind)到 bean 属性。

我尝试创建一个全局 Binder 。

我不知道我做错了什么。

@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));
    }
}

但这并不能解决我的问题。在我的 Controller 中我总是遇到错误:

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]]

你能告诉我出了什么问题吗?

谢谢。

最佳答案

寻找解决方案。

正如拉尔夫在此评论中所说的那样 Timestamp Spring conversion非常清楚。

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

我通过重写 CustomDateEditor 并在 setAsText 方法中实例化一个新的时间戳而不是 java.util.date 来完成我自己的属性编辑器类。而且效果很好。

希望它能帮助别人。

关于java - spring mvc 对象时间戳绑定(bind)中的字段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32806139/

相关文章:

java - Hibernate 5 和 Spring 4 MVC 中的 SessionFactory NoClassDefFoundError

java - 为什么大公司更喜欢 Spring 而不是 Java EE?

java - 不使用主键检查 uniq 约束

java - Apache Camel 在 Camel split eip 后丢失跟踪 ID 和跨度 ID

java - 尽管 equals() 和 hashCode() 返回不同的值,Multimap 仍然在 containsValue() 上找到实例。怎么可能?

java - 如果用户同时具有两个角色,则允许访问 Spring Security 中的用户

java - Spring @Value 注释总是评估为空?

java - 是否可以以编程方式将 ScrollPane 滚动到给定位置?

java - 是否可以将包中的所有类注册为 Spring bean

spring - 如何在 spring-rest-oauth 中基于 oauth 范围限制方法访问?