1. Introduction
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
tag, - form could be associated with Java object provided in
th:object
attribute - this object is called command object, - command object properties can be attached to inputs using
th:field
attribute, - action could be specified using Thymeleaf attribute
th:action
or simplyaction
.
Hidden fields are similar to regular one the different is in type. For hidden fields we used type="hidden"
:
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 /
or /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.
Using th:field
is one of the way to assign a value to a hidden input, but we could use also:
simple
name
attribute:or
th:attr
Thymeleaf attribute:
3. Conclusion
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.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}