Spring validation: cannot convert from String to Date

I do a spring form validation, but I get:

Failed to convert property value of type 'java.lang.String' to required type 'ja
va.util.Date' for property 'birthdate'; nested exception is java.lang.Illega
lStateException: Cannot convert value of type [java.lang.String] to required typ
e [java.util.Date] for property 'birthdate': no matching editors or conversi
on strategy found

However, in my ModelAttribute form, I:

@NotNull
 @Past
 @DateTimeFormat(style="S-")
 private Date birthdate;

I thought DateTimeFormat is responsible for this?

I am using hibernate-validator 4.0.

+3
source share
2 answers

You have the option of using case CustomDateEditorin your controller to convert from string to date. Below is the example below in your controller, but you will need to change the date format to suit what you are using.


@InitBinder
    public void initBinder(WebDataBinder binder) {
        CustomDateEditor editor = new CustomDateEditor(new SimpleDateFormat("MM/dd/yyyy"), true);
        binder.registerCustomEditor(Date.class, editor);
    }
+9
source

@DateTimeFormat, FormattingConversionServiceFactoryBean. <mvc:annotation-driven> , , - :

<bean id="conversionService" 
    class="org.springframework.format.support.FormattingConversionServiceFactoryBean" /> 

<bean id="annotationMethodHandlerAdapter"    
    class="org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 
    <property name="webBindingInitializer">
        <bean id="configurableWebBindingInitializer"
            class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"> 
            <property name="validator"><ref bean="validator"/>
            <proeprty name = "conversionService" ref = "conversionService" />
        </bean>
    </property>
</bean>
+4

Source: https://habr.com/ru/post/1777430/


All Articles