Thymeleaf和SpringBoot-无法将类型[java.lang.String]的属性值转换为所需的类型[java.util.Date] [英] Thymeleaf and SpringBoot - Failed to convert property value of type [java.lang.String] to required type [java.util.Date] for prope

查看:738
本文介绍了Thymeleaf和SpringBoot-无法将类型[java.lang.String]的属性值转换为所需的类型[java.util.Date]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am building a web application using Thymeleaf and SpringBoot, I am new to both the technologies.

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

In my html file, there is a Date field as follows:

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

我的模型类具有与issueDate对应的字段,如下所示:

My model class has a field corresponding to issueDate as follows:

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

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

When I input a date from the UI, I see the following exception in the browser:

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

根据我的经验,我了解到UI会将属性读取为String,但是模型期望键入错误发生的日期。所以我需要将字符串转换为日期。但是,应该在哪里做呢?由于甚至在调用模型中的setter方法之前都会发生错误。

From my experience, I understand that the UI reads the property as a String, but the model expects a type Date due to which the error occurs. So I need to convert the String to a Date. However where should this be done? Since the error occurs even before the setter method in the model is invoked.

任何帮助将不胜感激!

Any help would be much appreciated! Thanks in advance!

推荐答案

在您的控制器中:

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

MM / dd / yyyy是您使用的日期格式

WHERE "MM/dd/yyyy" is the date format you're using.

这篇关于Thymeleaf和SpringBoot-无法将类型[java.lang.String]的属性值转换为所需的类型[java.util.Date]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆