我创建了一个带有事件表单对象的Spring Boot Controller。

    @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 / setter方法)
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。

最佳答案

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

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

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

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

07-28 03:37