【问题标题】:Spring validation: can't convert from String to Date春季验证:无法从字符串转换为日期
【发布时间】:2010-11-29 10:46:24
【问题描述】:

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

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。

【问题讨论】:

  • 你有<mvc:annotation-driven>吗?
  • 忘了说,这是在一个 portlet 中,所以 mvc:annotation-driven 不起作用。我使用: 跨度>

标签: spring hibernate-validator


【解决方案1】:

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


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

【讨论】:

    【解决方案2】:

    要使用@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>
    

    【讨论】:

      猜你喜欢
      • 2014-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多