【问题标题】:Spring Conversion in form backing bean表单支持 bean 中的 Spring 转换
【发布时间】:2017-10-11 15:17:20
【问题描述】:

我实际上有两个问题。两者都发生在相同的情况下,如下:

我正在使用 spring 和 thymeleaf,我想向服务器发布一个表单,它工作正常,但服务器无法将一些提交的数据转换为我的 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>

bean定义:

@lombok.Data
public class MyBean{
    private ZonedDateTime date;
    private MyType type;
}

问题:

  1. 日期输入的值无法转换为 java.time.ZonedDateTime
  2. 选择的值(将作为数字发布)无法转换为 MyType 类型的对象。因为 MyType 是一个 JPA 实体,并且为它定义了一个 org.springframework.data.repository.CrudRepository,所以我会对此进行扩展。

如果有人能帮助我,我会很高兴。

【问题讨论】:

    标签: spring spring-mvc spring-data-jpa thymeleaf java-time


    【解决方案1】:

    我自己解决了。

    日期输入的值作为字符串发送,即“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 注释我的应用程序,这反过来又为我的 Entity-Beans 注册了一些转换器

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-29
      • 2015-11-30
      • 2014-02-21
      • 2017-06-09
      • 2015-09-25
      • 1970-01-01
      • 2020-09-01
      相关资源
      最近更新 更多