【问题标题】:sent current date in Thymeleaf to variable将 Thymeleaf 中的当前日期发送到变量
【发布时间】:2016-03-18 10:32:52
【问题描述】:

我有 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')}"/>

小心:

这不是完美的解决方案:

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

【问题讨论】:

  • 如果您不想使用 Spring 绑定到您的输入,只需使用纯 HTML id 和 name 属性。此外,您不能使用 span 元素发布数据。您必须使用输入标签

标签: java spring date thymeleaf


【解决方案1】:

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

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

&lt;input type="text" th:field="*{updateDate}"/&gt;

【讨论】:

  • 谢谢 - 肯定是好答案。我想知道这样的事情是否可行:&lt;input th:field="*{updateDate}" th:attr="value =${#dates.format(#dates.createNow(), 'dd/MM/yyyy HH:mm')"/&gt;
猜你喜欢
  • 1970-01-01
  • 2015-04-28
  • 1970-01-01
  • 1970-01-01
  • 2015-07-02
  • 2021-03-09
  • 2018-04-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多