Using Thymeleaf in Spring Boot

In my previous post, I showed you how to use Thymeleaf in Spring MVC. Using Thymeleaf will be much simpler thanks to the Spring Boot mechanism. How is it in detail? In this tutorial, I will guide you on how to use Thymeleaf in Spring Boot.

First, I will create a new Spring Boot project with the Thymeleaf Starter dependencies as follows:

Using Thymeleaf in Spring Boot

with Web Starter and Thymeleaf Starter dependencies as follows:

Using Thymeleaf in Spring Boot

Result:

Using Thymeleaf in Spring Boot

Other than Using Thymeleaf in Spring MVC, in Spring Boot, we do not need to declare the SpringTemplateEngine, SpringResourceTemplateResolver, ThymeleafViewResolver objects in the Spring container manually. These objects have been Spring Boot with Thymeleaf Starter dependencies declared in the Spring container automatically. Our job is to declare the template files only.

If you check the src/main/resources directory in the project we just created, you will see a folder named templates. This is the directory that when we declare the Web Starter dependency, will be created with the Spring Boot project along with the static directory. By default, the ThymeleafAutoConfiguration class configures this directory to contain Thymeleaf’s template files. You can see the ThymeleafProperties class used in the ThymeleafAutoConfiguration class to better understand this.

To change this default directory, you can declare the spring.thymeleaf.prefix property in the application.properties file with the value that points to the directory where you included the template files. The default value of this property is “classpath:/templates/” so you understand why I said the src/main/resources/templates directory is the default directory containing the Thymeleaf template above, right?

Suppose I now add a file called home.html located in the src/main/resources/templates directory:

Using Thymeleaf in Spring Boot

with the following content:

then when I run the application with a Controller with the following content:

the results will look like this:

Using Thymeleaf in Spring Boot

Add Comment