我有一个输入字段(类型:“日期”)-我可以使用 Thymeleaf 将它映射到我的对象中的“LocalDate”字段吗?
目的
public class Project {
@Id
private int id;
private LocalDate startDate;
private LocalDate endDate;
}
HTML 输入
<form action="#"
th:action="@{|/admin/projects/add/save|}"
th:object="${newProjects}"
method="POST"
class="form-horizontal">
<input type="date" class="form-control" id="startDate"
placeholder="Project start"
th:field="*{startDate}"/>
<input type="date" class="form-control" id="endDate"
placeholder="Project start"
th:field="*{endDate}"/>
</form>
如何将输入字段正确映射到 LocalDate startDate 或 endDate?
控制器
//GetMapping for Projects is also there, but I didn't paste it to keep clarity
@PostMapping("/add/save")
public String saveProject(@Valid @ModelAttribute("project") Project project,
BindingResult bindingResult,
Model model,
RedirectAttributes redirectAttributes) {
// bindingResult has error, because Thymeleaf can't map from the input-field to startDate
if (!bindingResult.hasErrors()) {
project.save(project);
return "redirect:/admin/projects/list";
} else {
return "admin/projects/add";
}
}
例外
无法将类型“java.lang.String”的属性值转换为属性“startDate”所需的类型“java.time.LocalDate”;嵌套异常是 org.springframework.core.convert.ConversionFailedException:无法从类型 [java.lang.String] 转换为类型 [@javax.persistence.Column java.time.LocalDate] 的值 '2017-09-08';嵌套异常是 java.lang.IllegalArgumentException:值的解析尝试失败 [2017-09-08]