4

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

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 对此负责?

我正在使用休眠验证器 4.0。

4

2 回答 2

10

您可能必须在控制器中使用 register aCustomDateEditor才能将字符串转换为日期。下面的示例方法进入您的控制器,但您必须更改日期格式以匹配您正在使用的任何内容。


@InitBinder
    public void initBinder(WebDataBinder binder) {
        CustomDateEditor editor = new CustomDateEditor(new SimpleDateFormat("MM/dd/yyyy"), true);
        binder.registerCustomEditor(Date.class, editor);
    }
于 2010-11-29T11:15:50.203 回答
4

为了使用@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>
于 2010-11-29T11:41:01.833 回答