将序列化HTML时间字段转换为java.time.LocalTime
我创建了一个Spring引导控制器,它采用事件形式对象将序列化HTML时间字段转换为java.time.LocalTime,java,spring,spring-mvc,spring-boot,localtime,Java,Spring,Spring Mvc,Spring Boot,Localtime,我创建了一个Spring引导控制器,它采用事件形式对象 @RestController @RequestMapping("/Event") public class EventController { @RequestMapping(value = "/create", method = RequestMethod.POST) private synchronized List<Event> createEvent(Even
@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();
}
}
我在startTime和endTime字段上得到一个Spring类型不匹配错误
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。您需要在提交表单期间要转换的LocalTime
实例上提供注释。这些注释必须表明传入数据将遵循通用ISO时间格式:
在应用这些注释之前,我能够重现您看到的错误。应用这些注释后,我能够成功地将表单提交发布到您的代码示例中,并验证它是否正确创建了
LocalTime
实例。为我节省了大量时间。向上投票。请添加相关阅读资料(书籍或教程)。谢谢,@Vito,谢谢你的投票!我用来回答这个问题的唯一资源是答案中已经链接的JavaDoc页面。就更一般的阅读材料而言,我一直认为公开阅读是相当好的。
eventDate=27%2F01%2F2017&eventType=REN&maxParticipants=10&startTime=09%3A00&endTime=12%3A00
@DateTimeFormat(iso = DateTimeFormat.ISO.TIME)
private LocalTime startTime;
@DateTimeFormat(iso = DateTimeFormat.ISO.TIME)
private LocalTime endTime;