Form Binding in Thymeleaf
Thymeleaf makes it simple to bind form inputs to Java objects. Let's explore how to use th:object with dropdowns, radio buttons, and checkboxes.
Select Dropdowns
Use th:field with a <select> tag. Thymeleaf binds the selected value to the object property.
<form th:action="@{/save}" th:object="${user}" method="post">
<label for="country">Country:</label>
<select id="country" th:field="*{country}">
<option value="US">United States</option>
<option value="UK">United Kingdom</option>
<option value="NG">Nigeria</option>
</select>
<button type="submit">Save</button>
</form>
The selected option's value goes straight into user.country. If the user object already has a country set, Thymeleaf automatically selects the matching option.
Radio Buttons
Radio buttons let users pick one option from a group. Use the same th:field name for all radio inputs.
<form th:action="@{/save}" th:object="${user}" method="post">
<p>Gender:</p>
<input type="radio" id="male" th:field="*{gender}" value="Male"/>
<label for="male">Male</label>
<input type="radio" id="female" th:field="*{gender}" value="Female"/>
<label for="female">Female</label>
<button type="submit">Save</button>
</form>
Only one can be selected at a time. The chosen value binds to user.gender.
Checkboxes
Checkboxes allow multiple selections. They bind to a list property on your object.
<form th:action="@{/save}" th:object="${user}" method="post">
<p>Hobbies:</p>
<input type="checkbox" id="reading" th:field="*{hobbies}" value="Reading"/>
<label for="reading">Reading</label>
<input type="checkbox" id="gaming" th:field="*{hobbies}" value="Gaming"/>
<label for="gaming">Gaming</label>
<input type="checkbox" id="cooking" th:field="*{hobbies}" value="Cooking"/>
<label for="cooking">Cooking</label>
<button type="submit">Save</button>
</form>
The hobbies field should be a List<String> in your User object. Selected values are collected into that list.
The Command Object
The object you bind to is called a "command object." It's just a regular Java class with getters and setters.
public class User {
private String name;
private String country;
private String gender;
private List<String> hobbies = new ArrayList<>();
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getCountry() { return country; }
public void setCountry(String country) { this.country = country; }
public String getGender() { return gender; }
public void setGender(String gender) { this.gender = gender; }
public List<String> getHobbies() { return hobbies; }
public void setHobbies(List<String> hobbies) { this.hobbies = hobbies; }
}
Spring creates this object, Thymeleaf fills it from the form, and your controller receives the populated instance. That's form binding in a nutshell.