Getting Started With Thymeleaf In Spring Boot
Tutorial on how to run an HTML template using Thymeleaf starting from Spring Boot Application setup.
Join the DZone community and get the full member experience.Join For Free
Thymeleaf is a Java Template Engine which enables creation of web applications. It enables interaction between Java Classes and HTML/XML templates.
Thymeleaf Provides below Template Modes:
In this article we are going to get familiar with Thymeleaf and the set up starting from basic configurations.
If you already have a Spring Boot application ready, Skip to Step 2.
Create a Spring Boot Project. Using STS or Spring Initializr. While creating Spring Boot Project add dependency for Thymeleaf and Spring Web.
If you have used the Spring Initializr, unzip and Import Project in IDE.
For Gradle: Import -> Gradle -> Existing Gradle Project
For Maven: Import -> Maven -> Existing Maven Projects
Once Project is Set up we can get started with Implementing Thymeleaf.
Create a Controller Class in package. Either add a new package or use the default package containing main application class.
In the above class, we have created a Controller, and notified Spring Boot using
It is not recommended to use
@RestController in this scenario as it contains
@ResponseBody which binds method return value to response body. Hence its responses are interpreted differently than
Create a Get method using
@GetMapping and name the value as '
thymeleafTemplate', which is also going to be the name of the HTML template. The method
getTemplate accepts the name and model. Name will be passed to the template using the model. If no name is passed by the user, we are setting the default value 'World'.
Add a HTML template.
Add template in the resources folder. src/main/resources/templates/thymeleafTemplate.html
We are mapping the value received in GET request, in the template using
Run the application using IDE: Run as -> Spring Boot App
Or to run the code externally:
Create Jar files in the target directory using the below commands:
Once Code compiles and Jar file is created, start the application:
Server will run on default port 8080:
Once your application has started, hit the URL from the browser:
Now you can start building on this code and create your own web application.
To create an index.html include it in the static folder - src/main/resources/static. It will be the default html to run if we hit the brower with out specifying path:
To get started you can get the above project directly from ThymeLeaf Demo Project
IDE used for Development: STS 4
Opinions expressed by DZone contributors are their own.