将 Thymeleaf 中的当前日期发送到变量

sent current date in Thymeleaf to variable

我有 class X 字段:

@DateTimeFormat(pattern = "dd/MM/yyyy HH:mm")
private Date updateDate;

我有html方法="post"

<form class="form-horizontal" 
th:action="@{/x/save}" method="post">

我想获取当前日期并通过 POST 将其发送到 updateDate 字段:

<span th:text="${#dates.format(#dates.createNow(), 'dd/MM/yyyy HH:mm')}"
      th:value="${#dates.format(#dates.createNow(), 'dd/MM/yyyy HH:mm')}"
      th:id="*{updateDate}" th:name="*{updateDate}">
</span>

问题是日期没有通过 POST 发送到 updateDate 字段。我通过 Developer Tools 在浏览器中检查了它。 我不能在这里只使用 th:field 因为我想要当前日期并且我通过以下方式获取它:

th:value="${#dates.format(#dates.createNow(), 'dd/MM/yyyy HH:mm')}"

像这样它也不是通过POST发送的:

<input th:text="${#dates.format(#dates.createNow(), 'dd/MM/yyyy HH:mm')}"
       th:value="${#dates.format(#dates.createNow(), 'dd/MM/yyyy HH:mm')}"
       th:id="${updateDate}" th:name="${updateDate}"/>

但我在 html 中看到了正确的日期。

解法:

<input name="updateDate" id="updateDate"
       th:value="${#dates.format(#dates.createNow() , 'dd/MM/yyyy HH:mm')}"/>

注意:

这不是完美的解决方案:

  1. 用户可以通过 HTML 在发布前更改时间来操纵时间。
  2. 用户可以在 21.03 打开表格,等待 24 小时然后发送,时间仍然是 21.03 ..

如果您不想使用 Spring 绑定到您的输入,只需使用简单的 HTML id 和 name 属性。此外,您不能将 span 元素用于 post 数据。您必须使用输入标签。例如 <input name="updateDate" id="updateDate" th:value="${#dates.format(#dates.createNow() , 'dd/MMM/yyyy HH:mm')}"/>

更好的方法是在控制器中设置 updateDate 值并使用 Spring 数据绑定语法。

<input type="text" th:field="*{updateDate}"/>