Search code examples
javaspringdatethymeleaf

sent current date in Thymeleaf to variable


i have class X with field:

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

I have html with method="post"

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

I want to get current date and sent it via POST to updateDate field:

<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>

the problem is that date is not sent via POST to the updateDate field. I checked it in browser via Developer Tools. I can not use only th:field here cause i want current date and i acquire it via:

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

like this it is also not sent via 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}"/>

But I see correct date in html.

Solution:

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

Beware:

this is not perfect solution:

  1. user can manipulate time via HTML changing it before posting.
  2. user can open form on 21.03, wait 24 hours and then sent it and the time still will be 21.03 ..

Solution

  • If you dont want to use Spring for binding to your input just use plain HTML id and name attributes. Also you cannot use a span element to post data. You have to use an input tag. eg <input name="updateDate" id="updateDate" th:value="${#dates.format(#dates.createNow() , 'dd/MMM/yyyy HH:mm')}"/>

    A better approach is to set your updateDate value in the controller and using Spring data binding syntax.

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