2015-09-27 102 views
1

我正在使用spring 4.1.7.RELEASE。spring mvc对象时间戳绑定中的字段错误

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

但这不能解决我problem.In我的控制,我总是有错误:

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

你能告诉我有什么不对?

谢谢。

回答

0

寻找解决方案。

正如拉尔夫在此评论中所说Timestamp Spring conversion这很清楚。

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

我已经做了自己的属性编辑器类,通过覆盖CustomDateEditor并实例化一个新的Timestamp而不是java.util.date中的setAsText方法。它工作正常。

希望它能帮助别人。