春季更改日期输入格式

lma*_*gon 2 spring spring-mvc java-ee

我正在尝试创建一个表单,它将发送一个带有时间戳的对象.现在,输入格式必须是yyyy-MM-dd HH:mm:ss,我希望以格式输入时间戳dd.MM.yyyy HH:mm- 如何更改输入格式?

对象类:

public class Test {
    private Timestamp dateStart;

    public Timestamp getDateStart() {
        return dateStart;
    }
    public void setDateStart(Timestamp dateStart) {
        this.dateStart = new Timestamp(dateStart.getTime());
    }
}
Run Code Online (Sandbox Code Playgroud)

控制器方法:

@RequestMapping(value="test", method = RequestMethod.POST)
public View newTest(@ModelAttribute("test") Test test, Model model) {
    //save the Test object
}
Run Code Online (Sandbox Code Playgroud)

jsp表单:

<form:form action="service/test" method="post" modelAttribute="test">
    <form:input type="text" path="dateStart" />
</form:form>
Run Code Online (Sandbox Code Playgroud)

当格式不正确时,我收到此错误:

Field error in object 'test' on field 'dateStart': rejected value [22.05.2012 14:00]; codes [typeMismatch.test.dateStart,typeMismatch.dateStart,typeMismatch.java.sql.Timestamp,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [test.dateStart,dateStart]; arguments []; default message [dateStart]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.sql.Timestamp' for property 'dateStart'; nested exception is org.springframework.core.convert.ConversionFailedException: Unable to convert value "22.05.2012 14:00" from type 'java.lang.String' to type 'java.sql.Timestamp'; nested exception is java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]]
Run Code Online (Sandbox Code Playgroud)

lma*_*gon 10

感谢Tomasz我得到了答案,我必须向控制器添加一个binder方法:

@InitBinder
public void binder(WebDataBinder binder) {binder.registerCustomEditor(Timestamp.class,
    new PropertyEditorSupport() {
        public void setAsText(String value) {
            try {
                Date parsedDate = new SimpleDateFormat("dd.MM.yyyy HH:mm").parse(value);
                setValue(new Timestamp(parsedDate.getTime()));
            } catch (ParseException e) {
                setValue(null);
            }
        }
    });
}
Run Code Online (Sandbox Code Playgroud)