我正在做一些春季表格验证,但是我得到了:

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

但是,在我的Modelattribute形式中,我有:

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

我以为DateTimeFormat对此负责?

我正在使用Hibernate-Validator 4.0。

有帮助吗?

解决方案

有机会您必须使用注册 CustomDateEditor 在您的控制器中,从字符串转换为日期。下面的示例方法包含在您的控制器中,但是您必须更改日期格式以匹配所使用的任何内容。


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

其他提示

为了使用 @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>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top