表单支持bean中的Spring转换
我实际上有两个问题。两者发生在相同的情况下,如下所示: 我正在使用spring和thymeleaf,我想在服务器上发布一个表单,这很好,但服务器无法将提交的一些数据转换为我的bean的属性类型 表格:表单支持bean中的Spring转换,spring,spring-mvc,spring-data-jpa,thymeleaf,java-time,Spring,Spring Mvc,Spring Data Jpa,Thymeleaf,Java Time,我实际上有两个问题。两者发生在相同的情况下,如下所示: 我正在使用spring和thymeleaf,我想在服务器上发布一个表单,这很好,但服务器无法将提交的一些数据转换为我的bean的属性类型 表格: <form th:action="@{/demo}}" th:object="${myBean}" method="post"> <label>date</label> <input type="date" th:field="*{date
<form th:action="@{/demo}}" th:object="${myBean}" method="post">
<label>date</label>
<input type="date" th:field="*{date}">
<label>type</label>
<select th:filed="*{type}">
<option th:each="type: ${types}" th:value="${type.id}" th:text="${type.name}"></option>
</select>
<button type="submit">Submit</button>
</form>
问题:
org.springframework.data.repository.crudepository
public class ZonedDateTimeConverter implements Converter<String, ZonedDateTime> {
@Override
public ZonedDateTime convert(String source) {
return ZonedDateTime.of(LocalDate.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd")), LocalTime.of(00, 00),
ZoneId.systemDefault());
}
对于第二个问题,解决方案甚至更简单,我要做的唯一一件事就是用@EnableSpringDataWebSupport
注释我的应用程序,这反过来又为我的实体bean注册了一些转换器
public class ZonedDateTimeConverter implements Converter<String, ZonedDateTime> {
@Override
public ZonedDateTime convert(String source) {
return ZonedDateTime.of(LocalDate.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd")), LocalTime.of(00, 00),
ZoneId.systemDefault());
}
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new ZonedDateTimeConverter());
}