将序列化HTML时间字段转换为java.time.LocalTime

时间:2017-01-22 19:19:00

标签: java spring spring-mvc spring-boot localtime

我创建了一个Spring Boot Controller,它接受一个Event表单对象。

    @RestController
    @RequestMapping("/Event")
    public class EventController {

        @RequestMapping(value = "/create", method = RequestMethod.POST) 
        private synchronized List<Event> createEvent(Event inEvent) {       
            log.error("create called with event: " + inEvent);
            create(inEvent);
            return listAll();
        }
    }

Event类看起来像这样(省略了getters / setters)

public final class Event {
   private Integer id;
   private Integer periodId;
   private String name;
   @DateTimeFormat(pattern = "dd/MM/yyyy")
   private LocalDate eventDate;
   private LocalTime startTime;
   private LocalTime endTime;
   private Integer maxParticipants;
   private String status;
   private String eventType;  
}

我在startTime和endTime字段上遇到Spring Type不匹配错误

Field error in object 'event' on field 'endTime': rejected value
[12:00] codes
 [typeMismatch.event.endTime,typeMismatch.endTime,typeMismatch.java.time.LocalTime,typeMismatch]
arguments
[org.springframework.context.support.DefaultMessageSourceResolvable:
codes [event.endTime,endTime] arguments [] default message [endTime]]
default message [Failed to convert property value of type
'java.lang.String' to required type 'java.time.LocalTime' for property
'endTime' nested exception is
org.springframework.core.convert.ConversionFailedException: Failed to
convert from type [java.lang.String] to type [java.time.LocalTime] for
value '12:00' nested exception is java.lang.IllegalArgumentException:
Parse attempt failed for value [12:00]]

使用jQuery AJAX方法发布序列化表单数据。序列化数据如下所示:

eventDate=27%2F01%2F2017&eventType=REN&maxParticipants=10&startTime=09%3A00&endTime=12%3A00

如何让Spring正确解析序列化时间字段?

我使用的是Java 8。

1 个答案:

答案 0 :(得分:5)

您需要在表单提交期间要转换的LocalTime个实例上提供DateTimeFormat注释。这些注释必须表明传入的数据将遵循通用的ISO时间格式:DateTimeFormat.ISO.TIME

@DateTimeFormat(iso = DateTimeFormat.ISO.TIME)
private LocalTime startTime;

@DateTimeFormat(iso = DateTimeFormat.ISO.TIME)
private LocalTime endTime;

在我应用这些注释之前,我能够重现您看到的错误。在我应用这些注释后,我能够成功地将表单提交发布到您的代码示例,并验证它是否正确创建了LocalTime个实例。