Thymeleaf is a Java-based template engine used to process documents like HTML, XML, and others. It is one of the most popular libraries used to generate dynamic websites in Java applications. In this article we are going to present how to use hidden inputs in Thymeleaf templates.
2. Thymeleaf forms
Let's start with creating a simple form in Thymeleaf and break it down into its components.
There are several important aspects we need to explain here:
- every form in Thymeleaf used a simple HTML
- form could be associated with Java object provided in
th:objectattribute - this object is called command object,
- command object properties can be attached to inputs using
- action could be specified using Thymeleaf attribute
Hidden fields are similar to regular one the different is in type. For hidden fields we used
Java object associated with this form has the following structure:
Now let's have a look at a simple controller that could handle GET and POST requests:
Every GET request to the root context
/posts path will present a form associated with a brand new
Post object filled with a unique
id. POST requests handled by the
save method are intended to save post data submitted in HTML form.
th:field is one of the way to assign a value to a hidden input, but we could use also:
In this article, we presented how to create a form with hidden fields in Thymeleaf. We showed several ways to achieve that in a real-life but simple example.
As usual, all the code examples used in this tutorial can be found over on Github.