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

标签 java spring spring-mvc spring-boot localtime

我创建了一个 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/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 类型不匹配错误

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 实例。

关于java - 将序列化的 HTML 时间字段转换为 java.time.LocalTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41795135/

相关文章:

java - "W/AudioFlinger( 34): write blocked for 70 msecs, 2236 delayed writes, thread "是什么意思?

java - Playframework renderJSON() 数组

java - Spring的NamedParameterJDBCTemplate加入Hibernate的 session ?

Zuul 2 的 Spring 计划

java - Spring MVC 应用程序可以是多线程的,即使它的 servlet 不是吗?

java - 在 Java 中哪里可以得到 "UTF-8"字符串文字?

java - 添加二进制数,如 Java 中的十进制数。例如 0101 + 0110 = 0211

sql-server - 当我添加 sql 脚本时,Spring Boot 不起作用

java - 使用 Spring MVC 通过 AJAX 发送 HTML 数据

java - 如何确定java Web应用程序中资源的路径