Worldscope

Spring Boot Thymeleaf

Palavras-chave:

Publicado em: 05/08/2025

Spring Boot Thymeleaf: Dynamic Web Pages with Ease

This article explores how to integrate Thymeleaf, a modern server-side Java template engine, with Spring Boot to create dynamic and interactive web pages. We'll cover the core concepts, implementation, and alternative approaches to leveraging Thymeleaf's power within a Spring Boot application.

Fundamental Concepts / Prerequisites

To effectively follow this guide, you should have a basic understanding of the following:

  • Spring Boot: Familiarity with Spring Boot's auto-configuration, dependency management, and overall structure.
  • HTML: A solid grasp of HTML syntax and structure.
  • Java: Basic Java programming concepts, including classes, objects, and methods.
  • Maven or Gradle: Experience with dependency management tools.

Core Implementation

This section demonstrates how to set up a simple Spring Boot application that uses Thymeleaf to render a dynamic web page.


// Spring Boot Application Class
@SpringBootApplication
@Controller
public class ThymeleafDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(ThymeleafDemoApplication.class, args);
    }

    @GetMapping("/hello")
    public String hello(Model model) {
        // Add data to the model that will be accessible in the Thymeleaf template
        model.addAttribute("message", "Hello, Thymeleaf!");
        model.addAttribute("currentTime", new java.util.Date());

        // Return the name of the Thymeleaf template (without the .html extension)
        return "hello";
    }
}

// Thymeleaf Template (hello.html - Located in src/main/resources/templates)
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Thymeleaf Demo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <h1 th:text="${message}">Default Message</h1>
    <p>The current time is: <span th:text="${currentTime}"></span></p>
</body>
</html>

//pom.xml dependencies (Maven)
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Code Explanation

Spring Boot Application: The @SpringBootApplication annotation marks this class as the entry point of our Spring Boot application. The @Controller annotation designates it as a web controller, handling incoming HTTP requests.

hello() Method: The @GetMapping("/hello") annotation maps HTTP GET requests to the /hello path to this method. It retrieves a Model object, which is used to pass data from the controller to the Thymeleaf template. We add two attributes: message (a string) and currentTime (a Date object). The method returns the string "hello", which corresponds to the name of the Thymeleaf template file (hello.html) located in the src/main/resources/templates directory. Spring Boot automatically configures Thymeleaf to look for templates in this location.

Thymeleaf Template (hello.html): This HTML file contains Thymeleaf expressions. The xmlns:th="http://www.thymeleaf.org" attribute is crucial; it declares the Thymeleaf namespace. The th:text="${message}" attribute tells Thymeleaf to replace the text content of the <h1> tag with the value of the message attribute from the model. Similarly, th:text="${currentTime}" replaces the text content of the <span> tag with the value of the currentTime attribute.

pom.xml Dependencies: The spring-boot-starter-thymeleaf dependency automatically configures Thymeleaf for use in your Spring Boot application. spring-boot-starter-web provides the necessary components for building web applications, including Spring MVC.

Complexity Analysis

The complexity of using Thymeleaf is primarily related to the size and complexity of the template itself.

Time Complexity: Rendering a Thymeleaf template depends on the template's size and the complexity of the expressions within it. In most cases, the rendering time is relatively quick, suitable for real-time web applications. The Spring framework handles the preprocessing and caching to optimize performance. The most expensive operations are the evaluation of the expressions to insert the data into the template.

Space Complexity: The space complexity mainly depends on the size of the template and the amount of data passed to the template for rendering. Spring's caching mechanisms also contribute to the space usage, but they aim to optimize performance by storing frequently used templates in memory.

Alternative Approaches

While Thymeleaf is a popular and powerful choice, other template engines can be used with Spring Boot. One alternative is:

FreeMarker: FreeMarker is another widely used template engine that offers similar features to Thymeleaf. It supports dynamic content generation and provides a rich set of directives for controlling the template rendering process. The trade-off is that the syntax is slightly different from HTML, which might require a steeper learning curve for developers already familiar with HTML and Thymeleaf's natural templating.

Conclusion

Thymeleaf offers a clean and efficient way to build dynamic web pages within a Spring Boot application. Its natural templating approach, integration with Spring MVC, and robust feature set make it an excellent choice for many web development projects. By leveraging Thymeleaf's expressions and Spring Boot's auto-configuration, developers can create interactive and data-driven web applications with ease. This guide covers the basics of integration and using Thymeleaf with Spring Boot, giving a solid foundation for more complex projects.