Search code examples
javaspringspring-mvcspring-bootlocaltime

Convert serialized HTML time field to java.time.LocalTime


I have created a Spring Boot Controller that takes an Event form object.

    @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();
        }
    }

The Event class looks like this (getters/setters omitted)

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;  
}

I am getting a Spring Type mismatch error on the startTime and endTime fields

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]]

The serialized form data is posted using a jQuery AJAX method. The serialized data looks like this:

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

How can I get Spring to correctly parse the serialized time fields ?

I am using Java 8.


Solution

  • You'll need to supply a DateTimeFormat annotation on the LocalTime instances that you want to convert during the form submission. Those annotations must indicate that the incoming data will adhere to the common ISO time format: DateTimeFormat.ISO.TIME.

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

    Before I applied those annotations, I was able to reproduce the error you saw. After I applied those annotations, I was able to POST a form submission to your code sample successfully and verify that it created the LocalTime instances correctly.