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:
with Web Starter and Thymeleaf Starter dependencies as follows:
Result:
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:
with the following content:
1 2 3 4 5 6 7 8 9 10 11 12 |
<html xmlns:th="http://www.thymeleaf.org"> <head> <title>Home</title> </head> <body> <h1>Hello world!</h1> <P> The time on the server is <label th:text="${serverTime}"></label> </P> </body> </html> |
then when I run the application with a Controller with the following content:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package com.huongdanjava.springbootthymeleaf; import java.text.DateFormat; import java.util.Date; import java.util.Locale; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class HomeController { @RequestMapping(value = "/", method = RequestMethod.GET) public String home(Locale locale, Model model) { Date date = new Date(); DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale); String formattedDate = dateFormat.format(date); model.addAttribute("serverTime", formattedDate ); return "home"; } } |
the results will look like this: