我有 X 类字段:
@DateTimeFormat(pattern = "dd/MM/yyyy HH:mm")
private Date updateDate;
我有带有 method="post"的 html
<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')}"/>
注意:
这不是完美的解决方案:
- 用户可以在发布前通过 HTML 更改时间来操纵时间。
- 用户可以在 21.03 打开表格,等待 24 小时然后发送,时间仍然是 21.03 ..
最佳答案
如果您不想使用 Spring 绑定(bind)到您的输入,只需使用纯 HTML id 和 name 属性。您也不能使用 span 元素发布数据。您必须使用输入标签。例如<input name="updateDate" id="updateDate" th:value="${#dates.format(#dates.createNow() , 'dd/MMM/yyyy HH:mm')}"/>
更好的方法是在 Controller 中设置 updateDate 值并使用 Spring 数据绑定(bind)语法。
<input type="text" th:field="*{updateDate}"/>
关于java - 将 Thymeleaf 中的当前日期发送到变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36082060/