How to Use Thymeleaf in a Spring Boot Web Application?

Thymeleaf is a popular templating engine for web applications in Spring Boot. Here's a step-by-step guide on how to integrate Thymeleaf into a Spring Boot web application.

1. Add the Required Dependency

Add the Thymeleaf starter dependency to your project. 

Maven:

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

Gradle:

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

2. Create Thymeleaf Templates

By default, Spring Boot looks for Thymeleaf templates under the src/main/resources/templates directory. For instance, create a new file named hello.html inside src/main/resources/templates:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Thymeleaf Example</title>
</head>
<body>
    <h1 th:text="'Hello, ' + ${name} + '!'">Hello, World!</h1>
</body>
</html>

3. Create a Controller

Now, create a Spring MVC controller to render the Thymeleaf template.

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloController {

    @GetMapping("/hello")
    public String hello(Model model) {
        model.addAttribute("name", "John Doe");
        return "hello";
    }
}

In this example, when a user accesses /hello, they'll be greeted with "Hello, John Doe!". 

4. Customize Thymeleaf Configuration (Optional)

If you need to customize Thymeleaf configurations, you can do so by adding properties in application.properties or application.yml. For example, to change the cache setting for templates in application.properties:

spring.thymeleaf.cache=false

This might be useful during development to see template changes without restarting the application. 

5. Start Your Application

Run your Spring Boot application, and if you navigate to http://localhost:8080/hello, you'll see your Thymeleaf template in action! 


Comments