简体   繁体   中英

spring mvc Field error in object timestamp binding

I'm using spring 4.1.7.RELEASE.

I can't bind date element to a bean property.

I've tried creating a global binder.

I don't know what i'm doing wrong.

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

But this not solve my problem.In my controller I always have the error :

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

Can you tell me what's wrong ?

Thank you.

Find a solution.

As Ralph said in this comment Timestamp Spring conversion It's very clear.

CustomDateEditor convert a string to java.util.Date (and not to java.sql.Timestamp).

I have done my own property editor class by overriting CustomDateEditor and instanciate a new Timestamp instead of java.util.date ine the setAsText Method. And it works fine.

Hope it help someone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM