java - 将 HTML 输入日期映射到 Java 对象的 LocalDate

标签 java spring-boot thymeleaf localdate

我有一个输入字段(类型:“日期”) - 谁可以使用 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?

Controller

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

异常

Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDate' for property 'startDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@javax.persistence.Column java.time.LocalDate] for value '2017-09-08'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2017-09-08]

最佳答案

您有几个选择:

1 - 尝试:

@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate startDate;

@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate endDate;

2 - Use Thymeleaf Extras

关于java - 将 HTML 输入日期映射到 Java 对象的 LocalDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46414394/

相关文章:

spring - 如何在代理后面设置 Spring Boot CLI

java - 如何使用 Pageable 在 Spring Boot 和 Thymeleaf 中显示按点赞数排序的技能列表?

spring - Playframework2就像 Spring 的反向路由

java - 沿 X 轴和 Z 轴实现相机旋转时出现问题

java - 如何在Gradle项目中使用Mybatis Pagehelper插件?

java - 将 Elasticsearch 升级到 5.6.3

java - RestTemplate Junit : Cannot invoke "org.springframework.http.ResponseEntity.getBody()" because "response" is null

java - 提交表单时收到接口(interface) java.util.List 未找到主要或默认构造函数?

java - 即使在java中执行return后也执行方法

java - 从 Excel 工作表读取数据时出现 NullpointerException