Spring验证:无法从String转换为Date

jac*_*ack 4 spring hibernate-validator

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

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
Run Code Online (Sandbox Code Playgroud)

但是,在我的modelAttribute表单中,我有:

@NotNull
 @Past
 @DateTimeFormat(style="S-")
 private Date birthdate;
Run Code Online (Sandbox Code Playgroud)

我以为DateTimeFormat对此负责?

我正在使用hibernate-validator 4.0.

Nia*_*son 10

您有可能必须CustomDateEditor在控制器中使用寄存器a 将字符串转换为日期.下面的示例方法在您的控制器中,但您必须更改日期格式以匹配您正在使用的任何内容.


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