春天转换成表格支持bean
问题描述:
我其实有两个问题。两者都发生在相同的情况下,如下所示:春天转换成表格支持bean
我正在与春天和thymeleaf,我想发布一个窗体到服务器,这工作正常,但服务器无法转换一些submited数据到我的bean属性的类型。
形式:
<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>
的的BeanDefinition:
@lombok.Data
public class MyBean{
private ZonedDateTime date;
private MyType type;
}
问题:
- 日期输入的值不能转化为java.time.ZonedDateTime
- select(它将作为数字发布)的值ca n不能转换为MyType类型的对象。我会推测这是因为MyType是一个JPA实体,并为其定义了一个
org.springframework.data.repository.CrudRepository
。
如果你们中的任何一位能帮助我,我会很高兴。
答
我自己解决了它。
日期输入的值是以字符串形式发送的,即“2017-12-31”为了能够在我的表单支持bean中使用ZonedDateTime,我必须注册一个自定义转换器。这里是代码:
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());
}
}
,并在WebMvcConfigurer
我用它注册:
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new ZonedDateTimeConverter());
}
对于第二个问题的解决办法是更简单的,我唯一佩服做的是用@EnableSpringDataWebSupport
注释我的应用程序,然后我的实体豆注册一些转换器