首页 文章

LocalDate形式

提问于
浏览
4

我有一个关于Spring Thymeleaf日期格式的问题 . 我有一个带有 LocalDate date 字段的简单实体 . 我希望从表单中的用户获取此日期并将其保存到MySQL数据库 . 我收到这样的错误:

无法将类型java.lang.String的属性值转换为属性日期所需的类型java.time.LocalDate;嵌套异常是org.springframework.core.convert.ConversionFailedException:无法从类型java.lang.String转换为类型java.time.LocalDate,值为2019-04-30;嵌套异常是java.time.format.DateTimeParseException:无法在索引2处解析文本2019-04-30

我的实体:

@Entity
@Table(name="game")
public class Game{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @Transient
    private User gameOwner;
    private LocalDate date;
    private LocalTime time;

    //other fields

Thymeleaf观点/形式:

<form action="#" th:action="@{/games/addForm}" th:object="${gameForm}" method="post">    
    <p>Date: <input type="date" th:field="*{date}" /></p>
</form>

这个问题的原因是什么?也许还有其他更好的存储日期方式?

3 回答

  • 1

    问题解决了..我不知道为什么,但改变我的模板:

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

    并将 @DateTimeFormat(pattern = "yyyy-MM-dd") 添加到实体字段解决了问题 .

  • 1

    Thymeleaf为此提供了额外的模块:https://github.com/thymeleaf/thymeleaf-extras-java8time

    添加以下依赖项(maven)就足够了:

    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-java8time</artifactId>
    </dependency>
    
  • 7

    我无法重现确切的错误,但我相信为LocalDate类添加自定义编辑器应该解决这个问题 . 将此方法添加到您的控制器:

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
      binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) throws IllegalArgumentException{
          setValue(LocalDate.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        }
    
        @Override
        public String getAsText() throws IllegalArgumentException {
          return DateTimeFormatter.ofPattern("yyyy-MM-dd").format((LocalDate) getValue());
        }
      });
    }
    

    它's also possible to add this globally, you'必须创建一个 ControllerAdvice 类并在那里添加方法 .

相关问题