1. Introduction
Thymeleaf is one of the most popular template engines in the Java ecosystem. It allows us to easily use data from our Java applications to create dynamic HTML pages.
In this tutorial, we’ll look at several ways to use hidden inputs with Spring and Thymeleaf.
2. Thymeleaf with HTML Forms
Before we look at working with hidden fields, let’s take a step back and look at how Thymeleaf works with HTML forms in general.
The most common use case is to use an HTML form that maps directly to a DTO in our application.
For example, let’s assume we’re writing a blog application and have a DTO that represents a single blog post:
class BlogDTO {
long id;
String title;
String body;
String category;
String author;
Date publishedDate;
}
We can use an HTML form to create a new instance of this DTO using Thymeleaf and Java:
<form action="#" method="post" th:action="@{/blog}" th:object="${blog}">
<input type="text" th:field="*{title}">
<input type="text" th:field="*{category}">
<textarea th:field="*{body}"></textarea>
</form>
Notice that the fields in our blog-post DTO map to a single input in the HTML form. This works well in most cases, but what fields shouldn’t be editable? This is where hidden inputs can help.
For example, each blog post has a unique ID field that users should not be allowed to edit. Using hidden inputs, we can pass the ID field into the HTML form without allowing it to be displayed or edited.
3. Using the th:field Attribute
The quickest way to assign a value to a hidden input is to use the th:field attribute:
<input type="hidden" th:field="*{blogId}" id="blogId">
This is the simplest way because we don’t have to specify the value attribute, but it may not be supported in older versions of Thymeleaf.
4. Using the th:attr Attribute
The next way we can use hidden inputs with Thymeleaf is using the built-in th:attr attribute:
<input type="hidden" th:value="${blog.id}" th:attr="name='blogId'"/>
In this case, we have to reference the id field using the blog object.
5. Using the name Attribute
Another less verbose approach is to use the standard HTML name attribute:
<input type="hidden" th:value="${blog.id}" name="blogId" />
It solely relies on standard HTML attributes. In this case, we also must reference the id field using the blog object.
6. Conclusion
In this tutorial, we looked at several ways to use hidden inputs with Thymeleaf. This is a useful technique for passing read-only fields from our DTOs into HTML forms.
As always, all the code examples used in this tutorial can be found over on Github.