春天与百里香叶绑定日期在html形式



>我有一个简单的表单片段,如下所示:

<form th:action="@{'/save'}" th:object="${account}" method="post">
<div class="form-group">
<label for="expirationDate">Expiration date</label>
<input type="datetime-local" class="form-control" id="expirationDate"
placeholder="Expiration date" th:field="*{expirationTime}"/>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>

我正在向那里传递一个填充对象accountexpirationTime这是一个LocalDateTime字段。问题是expirationTime没有与传递给表单的值绑定(传递的对象是 100% 正确的(。 知道为什么吗?

编辑:简单地说,Spring/Thymeleaf没有为datetime本地输入类型正确格式化Java 8日期。 告诉 Spring 如何使用 @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm"( 正确格式化值。


注释@DateTimeFormat告诉 Thymeleaf 如何在解析/格式化时格式化日期字符串。这包括在 HTML 输入中生成 value= 注释,以及在表单提交的 POST 数据中读取。日期时间本地输入类型需要一个格式化为 yyyy-MM-dd'T'HH:mm 的值,因此我们将其用作模型类中的格式化程序。

型号类别:

public class DateContainer {
private String name;
@DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm")
private LocalDateTime dateTime;
public LocalDateTime getDateTime() {
return dateTime;
}
public void setDateTime(LocalDateTime dateTime) {
this.dateTime = dateTime;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

控制器:

@RequestMapping("/dateTest")
public String dateTest(final DateContainer dateContainer) {
if (dateContainer.getDateTime() == null) {
dateContainer.setDateTime(LocalDateTime.now());
}
return "dateTest";
}

模板:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org/">
<head></head>
<body>
<h1>Hello World!</h1>
<form th:action="@{/dateTest}" th:object="${dateContainer}">
<label>Name: </label><input type="text" th:field="*{name}"/>
<label>Date Time: </label><input type="datetime-local" th:field="*{dateTime}"/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>

HTML 生成:

<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Hello World!</h1>
<form action="/dateTest">
<label>Name: </label><input type="text" id="name" name="name" value="" />
<label>Date Time: </label><input type="datetime-local" id="dateTime" name="dateTime" value="2017-08-28T13:01" />
<input type="submit" value="Submit" />
<input type="hidden" name="_csrf" value="437b30dc-a103-44d0-b4e9-791d8de62986" /></form>
</body>
</html>

截图:

Chrome 60 中的屏幕截图

可比性:

日期时间本地输入类型是一种新的 HTML5 类型,并非所有浏览器都支持。 请参阅兼容性:https://caniuse.com/#search=datetime-local

在不兼容的浏览器中,日期时间本地字段将仅显示为文本字段,并将包含日期和时间,其中 T 介于两者之间。 这可能会导致可用性问题,具体取决于您的用例。

确保您具有以下依赖项:

<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>

之后,只需将 org.thymeleaf.extras.java8time.dialect.Java8TimeDialect 类添加到 TemplateEngine 实现中的方言列表中,您就可以在模板中使用 #temporals 对象。 更多细节可以在这里找到。

最新更新