带有 html 形式的 Thymeleaf 绑定日期的 Spring [英] Spring with Thymeleaf binding date in html form
问题描述
我有一个简单的表单片段,例如:
<button type="submit" class="btn btn-primary">提交</button></表单>
我正在传递一个填充对象 account
并且 expirationTime
是一个 LocalDateTime
字段.问题是 expirationTime
没有与传递给表单的值绑定(传递的对象是 100% 正确的).知道为什么吗?
简而言之,Spring/Thymeleaf 没有为日期时间本地输入类型正确格式化 Java 8 日期.告诉 Spring 如何使用 @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm") 正确格式化值.
<小时>注解@DateTimeFormat 告诉 Thymeleaf 在解析/格式化时如何格式化日期字符串.这包括在 HTML 输入中生成 value= 注释,以及读取表单提交的 POST 数据.datetime-local 输入类型需要一个格式为 yyyy-MM-dd'T'HH:mm 的值,因此我们将其用作模型类中的格式化程序.
模型类:
public class DateContainer {私人字符串名称;@DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm")私人本地日期时间日期时间;公共本地日期时间 getDateTime() {返回日期时间;}public void setDateTime(LocalDateTime dateTime) {this.dateTime = 日期时间;}公共字符串 getName() {返回名称;}公共无效集名称(字符串名称){this.name = 名称;}}
控制器:
@RequestMapping("/dateTest")公共字符串日期测试(最终日期容器日期容器){if (dateContainer.getDateTime() == null) {dateContainer.setDateTime(LocalDateTime.now());}返回日期测试";}
模板:
<html xmlns:th="http://www.thymeleaf.org/"><头></头><身体><h1>你好世界!</h1><form th:action="@{/dateTest}" th:object="${dateContainer}"><label>名称:</label><input type="text" th:field="*{name}"/><label>日期时间:</label><input type="datetime-local" th:field="*{dateTime}"/><input type="submit" value="提交"/></表单>