Receiving a LocalDateTime from an html form

0

Problem:

I'm trying to get a LocalDateTime of this input within a @Controller using a <form> that uses Thymeleaf.

<input class="form-control" id="dueDate" type="datetime-local" th:field="*{dueDate}"/>

But it always returns null , the other fields are working perfectly.

Object used to transfer data:

public class TaskDTO {
     private long id;
     @Size(min=8)
     @NotNull
     private String name;
     @Size(min=8)
     @NotNull
     private String description;
     @NotNull
     private String priority;
     @Size(min=8)
     @NotNull
     private String location;
     private boolean completed;
     @DateTimeFormat(pattern = "dd-MM-yyyy HH:mm")
     @NotNull
     private LocalDateTime dueDate;


     //getters e setters omitidos
}

I think it's not as relevant, but this is the controller:

@PostMapping("/dashboard/task/{id}")
public String TaskForm(@Valid @ModelAttribute("taskDTO")TaskDTO taskDTO,BindingResult bidingResult,@PathVariable("id")long id) {
    if(bidingResult.hasFieldErrors()) {
        //
    }
    Project p = projectRepository.findById(id).get();
    Task t = taskDTO.generateTask(p);
    taskRepository.save(t);
    return "main";
}
    
asked by anonymous 25.05.2018 / 02:56

1 answer

2

To work with the new Java 8 date API in Thymeleaf, you need two things you can check if they exist in your project:

1) a dependency with an extra module of Thymeleaf (note: the version of this dependency must be the same as that of Thymeleaf currently in use in the project.

//Se for projeto Maven
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-java8time</artifactId>
    <version>3.0.0.RELEASE</version>
</dependency>

//Se for projeto Gradle
compile group: 'org.thymeleaf.extras', name: 'thymeleaf-extras-java8time', version: '3.0.1.RELEASE'

2) a specific configuration of engine of Thymeleaf. In your case, you probably already have this method, so just include the indicated line:

private TemplateEngine templateEngine(ITemplateResolver templateResolver) {
    SpringTemplateEngine engine = new SpringTemplateEngine();
    engine.addDialect(new Java8TimeDialect()); //linha a ser adicionada
    engine.setTemplateResolver(templateResolver);
    return engine;
}

This may solve your problem. Here is some additional information you can take a look at too.

    
25.05.2018 / 14:27