【问题标题】:Thymeleaf and SpringBoot - Failed to convert property value of type [java.lang.String] to required type [java.util.Date] for propeThymeleaf 和 SpringBoot - 无法将类型 [java.lang.String] 的属性值转换为 prope 所需的类型 [java.util.Date]
【发布时间】:2016-12-07 04:25:53
【问题描述】:

我正在使用 Thymeleaf 和 SpringBoot 构建一个 Web 应用程序,我对这两种技术都是新手。

在我的html文件中,有一个日期字段如下:

<input type="date" th:field="*{issueDate}" />

我的模型类有一个对应issueDate的字段如下:

@NotNull(message = "Cannot be empty")
private Date issueDate;

当我从 UI 输入日期时,我在浏览器中看到以下异常:

    Failed to convert property value of type [java.lang.String] to required type [java.util.Date] for property issueDate;

根据我的经验,我了解 UI 将属性读取为字符串,但模型需要一个 Date 类型,因此会发生错误。所以我需要将字符串转换为日期。然而,这应该在哪里完成?因为错误甚至在模型中的 setter 方法被调用之前就发生了。

任何帮助将不胜感激!提前致谢!

【问题讨论】:

  • 能否请您展示您的控制器和更多的 html 文件。

标签: spring-boot datepicker thymeleaf


【解决方案1】:

在您的控制器中:

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("MM/dd/yyyy"), true));
}

其中“MM/dd/yyyy”是您使用的日期格式。

【讨论】:

  • 感谢您的回复,这很有效,因此不再抛出异常。但是,似乎没有正确解析日期,错误的日期存储在数据库中。我会检查一下。我想知道的另一件事是,这个 initBinder 方法什么时候被调用?它会在模型​​中的 setter 方法之前被调用吗?
  • 是的,这是整个过程的一部分。它在填充模型时由 spring 自动调用(在调用 setter 之前)。至于解析日期,您必须根据此规范将日期更改为我提供的格式(“MM/dd/yyyy”)为您使用的日期格式:docs.oracle.com/javase/8/docs/api/java/text/…
  • 再次感谢,这很有帮助。我也发现了日期问题,不知道为什么,但是需要日期格式为 yyyy-MM-dd,所以当我在 initBinder 中设置此日期格式时,它工作正常。我在表单中使用 html 日期类型作为输入,因此当用户输入日期时,它输入为 dd-MM-yyyy。所以不知道为什么 yyyy-MM-dd 有效!
猜你喜欢
  • 2018-08-21
  • 1970-01-01
  • 2014-07-05
  • 2017-05-06
  • 2015-03-29
  • 2021-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多