我正在用spring引导编写代码,这是一个网络项目。我也使用胸腺和引导。
我有一个模型,其中包含一个名为'validade‘的ZonedDateTime变量。在我的HTML/Thymeleaf文件中,我有一个数据报警器,允许您选择日期、月份和年份。
但是,当我单击submit时,会得到一个spring引导错误。我如何告诉spring引导将此日期转换为ZonedDateTime?我不能将这个变量更改为LocalDate或LocalDateTime。
有一个意外的错误(type=Bad请求,status=400)。对object=“tool”的验证失败。错误计数:1 org.springframework.validation.BeanPropertyBindingResult: 1在字段‘validade’上的对象‘工具’中的错误字段错误:拒绝值2021-01-08;代码typeMismatch.tool.validade、typeMismatch.validade、typeMismatch.java.time.ZonedDateTime、typeMismatch;参数[org.springframework.context.support.DefaultMessageSourceResolvable:代码tool.validade,validade;参数[];默认消息验证];默认消息[未能将'java.lang.String‘类型的属性值转换为属性’validade‘所需的'java.time.ZonedDateTime’类型;嵌套异常是org.springframework.core.convert.ConversionFailedException:未能从java.lang.String类型转换为值‘2021-01-08’的@org.springframework.format.annotation.DateTimeFormat @javax.persistence.Column java.time.ZonedDateTime;嵌套异常是java.lang.IllegalArgumentException:值2021-01-08的解析尝试失败]
<form method="POST" th:object="${tool}" th:action="@{/tools/add}">
...
<div lang="pt-br" class='date'>
<input th:value="${tool.validade}" th:field="${tool.validade}" lang="pt-br" id='data-validade' type='date' data-date-format="YYYY/MM/DD" class="form-control" />
</div>
...
</form>public class Tool{
...
@DateTimeFormat(pattern = "dd-MM-yyyy")
@Column(nullable = true, unique = false)
private ZonedDateTime validade;
}发布于 2021-01-02 15:23:01
解决方案是实现我自己的转换器并通知spring启动。下面的代码解决了这个问题。
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import org.springframework.boot.context.properties.ConfigurationPropertiesBinding;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
@Component
@ConfigurationPropertiesBinding
public class ZonedDateTimeConverter implements Converter<String, ZonedDateTime> {
@Override
public ZonedDateTime convert(String source) {
try {
if (source == null) {
return null;
}
if (source.contains(":") == false) {
LocalDate ld = LocalDate.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
ZonedDateTime atStartOfDay = ld.atStartOfDay(ZoneId.systemDefault());
return atStartOfDay;
} else {
return ZonedDateTime.parse(source);
}
} catch (Exception ex) {
//ex.printStackTrace();
}
return null;
}
}发布于 2020-12-25 20:20:43
模式是不正确的,根据您的日志,值2021-01-08被发送。这意味着日期遵循“yyyy”模式。
https://stackoverflow.com/questions/65451314
复制相似问题