Thymeleaf in Spring Boot: A Comprehensive Guide for Java Developers

Learn how to use Thymeleaf template engine in Spring Boot applications. From setup and core concepts to advanced features like fragments, layouts, and data binding.

Thymeleaf in Spring Boot: A Comprehensive Guide for Java Developers

Thymeleaf is a modern server-side Java template engine for both web and standalone environments. In a Spring Boot application, Thymeleaf is the go-to choice for generating dynamic HTML content, providing a natural template approach where templates can be viewed directly in a browser without a running server.

In this guide, we’ll explore everything you need to know to master Thymeleaf in Spring Boot — from basic setup to advanced layout management and form handling.

Why Choose Thymeleaf?

Before diving into the code, let’s understand why Thymeleaf is preferred over alternatives like JSP or FreeMarker:

  • Natural Templates — Thymeleaf templates are just standard HTML files. You can open them in any browser, and they will display correctly even before the server processes the expressions.
  • Spring Boot Integration — It offers first-class support for Spring Boot, including automatic configuration and integration with Spring Security.
  • Rich Expression Language — The Thymeleaf Standard Expression Language (Standard Dialect) is powerful and easy to learn.
  • Extensibility — You can create your own dialects and attribute processors if needed.

Setting Up Thymeleaf in Spring Boot

To get started, you need to add the Thymeleaf starter dependency to your pom.xml or build.gradle file.

Maven Dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Gradle Dependency

implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'

Spring Boot’s autoconfiguration will automatically set up the TemplateEngine and ViewResolver. By default, Thymeleaf looks for templates in the src/main/resources/templates directory.


Core Concepts: Standard Expression Syntax

Thymeleaf uses a specific syntax for its expressions. Understanding these four types is crucial:

1. Variable Expressions: ${...}

Used to access variables from the Spring model.

<p th:text="${user.name}">John Doe</p>

2. Selection Variable Expressions: *{...}

Used to access properties of a previously selected object (via th:object).

<div th:object="${user}">
    <p th:text="*{email}">john@example.com</p>
</div>

3. Message Expressions: #{...}

Used for internationalization (i18n) to retrieve messages from resource bundles.

<h1 th:text="#{welcome.message}">Welcome!</h1>

Used for generating URLs, automatically handling context paths.

<a th:href="@{/profile(id=${user.id})}">View Profile</a>

Attribute Processors

Thymeleaf provides several th:* attributes to control how HTML elements are rendered.

Conditional Rendering (th:if and th:unless)

<div th:if="${user.isAdmin}">
    <p>Welcome, Administrator!</p>
</div>
<div th:unless="${user.isActive}">
    <p>Account is inactive.</p>
</div>

Iteration (th:each)

<ul>
    <li th:each="product : ${products}">
        <span th:text="${product.name}">Product Name</span> - 
        <span th:text="${product.price}">$0.00</span>
    </li>
</ul>

Working with Forms and Data Binding

Thymeleaf excels at handling web forms in Spring Boot. It integrates seamlessly with Spring’s BindingResult for validation.

Controller Implementation

@Controller
public class UserController {

    @GetMapping("/register")
    public String showForm(Model model) {
        model.addAttribute("user", new User());
        return "registration-form";
    }

    @PostMapping("/register")
    public String submitForm(@ModelAttribute("user") User user) {
        // Process user registration
        return "success";
    }
}

HTML Template (registration-form.html)

<form th:action="@{/register}" th:object="${user}" method="post">
    <label>Name:</label>
    <input type="text" th:field="*{name}" />
    
    <label>Email:</label>
    <input type="email" th:field="*{email}" />
    
    <button type="submit">Register</button>
</form>

The th:field attribute automatically generates the id, name, and value attributes for the input field.


Advanced Layouts with Fragments

To avoid code duplication across multiple pages (like headers and footers), Thymeleaf provides fragments.

Defining a Fragment (common.html)

<div th:fragment="header">
    <nav>
        <a th:href="@{/}">Home</a>
        <a th:href="@{/about}">About</a>
    </nav>
</div>

Using a Fragment

<div th:replace="~{common :: header}"></div>
  • th:insert: Inserts the fragment content inside the host tag.
  • th:replace: Replaces the host tag with the fragment tag.
  • th:include: Similar to th:insert but only inserts the content of the fragment.

Conclusion

Thymeleaf is a powerful and flexible template engine that fits perfectly into the Spring Boot ecosystem. Its natural template approach, combined with rich expression syntax and advanced features like fragments, makes it an excellent choice for modern Java web development.

By mastering the concepts covered in this guide, you’ll be well on your way to building dynamic, maintainable, and robust web applications with Spring Boot and Thymeleaf.

Member discussion

0 comments

Start the conversation

Become a member of >hacksubset_ to start commenting.