Thymeleaf is a modern server-side Java template engine for both web and standalone environments. Its primary goal is to bring elegant and highly maintainable ways to create well-formed HTML, XML, JavaScript, CSS, and text documents. When integrated with Spring Boot, Thymeleaf provides a powerful and convenient way to build dynamic web applications.
Key Advantages of Thymeleaf:
- Natural Templating: Thymeleaf templates can be opened directly in a browser and displayed as static prototypes. This allows designers and developers to work on the same files without needing a running server. Thymeleaf adds its logic using special attributes, which are ignored by the browser when the file is opened statically.
- Spring Integration: Thymeleaf has excellent integration with Spring Framework and Spring Boot, offering features like seamless access to Spring's model, internationalization, Spring Security integration, and form handling.
- Extensibility: You can create custom dialects and processors to extend Thymeleaf's functionality to fit your specific needs.
- Performance: Thymeleaf is known for its good performance, especially when template caching is enabled in production environments.
-
Rich Feature Set: Thymeleaf offers a wide range of features, including:
- Variable Expressions: Accessing data passed from the controller.
- Selection Expressions: Navigating within a specific object.
- Message Expressions: Handling internationalization (i18n).
- Link URLs: Creating context-aware URLs.
- Fragment Expressions: Reusing parts of templates.
- Iteration: Looping through collections.
- Conditional Logic: Displaying content based on conditions.
- Form Handling: Binding form data to Java objects.
- Layout Dialect: Creating reusable page layouts.
Usage and Implementation in Spring Boot:
Here's a step-by-step guide on how to use and implement Thymeleaf in a Java Spring Boot application:
1. Add Thymeleaf Dependency:
In your pom.xml
(for Maven) or build.gradle
(for Gradle) file, add the spring-boot-starter-thymeleaf
dependency:
Maven (pom.xml
):
org.springframework.boot
spring-boot-starter-thymeleaf
Gradle (build.gradle
):
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
Spring Boot's auto-configuration will automatically set up Thymeleaf as your template engine once this dependency is included.
2. Create HTML Templates:
Place your HTML template files in the src/main/resources/templates
directory. Thymeleaf templates typically use the .html
extension (though other modes like .js
, .css
, .txt
, .xml
are also supported).
Example Template (src/main/resources/templates/greeting.html
):
</span>
xmlns:th="http://www.thymeleaf.org">
th:text="${title}">
th:text="${message}">
Enter fullscreen mode
Exit fullscreen mode
xmlns:th="http://www.thymeleaf.org": This XML namespace declaration is essential to use Thymeleaf attributes.
th:text="${title}": This Thymeleaf attribute replaces the content of the tag with the value of the title variable passed from the Spring controller.
th:text="${message}": Similarly, this replaces the content of the tag with the value of the message variable.
3. Create a Spring MVC Controller:Create a Spring MVC controller to handle web requests and pass data to your Thymeleaf templates.
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class GreetingController {
@GetMapping("/greeting")
public String greeting(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);
model.addAttribute("message", "Hello, " + name + "!");
model.addAttribute("title", "Greeting Page");
return "greeting"; // This refers to the greeting.html template
}
}
Enter fullscreen mode
Exit fullscreen mode
@Controller: This annotation marks the class as a Spring MVC controller.
@GetMapping("/greeting"): This maps HTTP GET requests to the /greeting path to the greeting method.
@RequestParam: This extracts the name request parameter from the URL. It's optional and defaults to "World".
Model model: Spring's Model object is used to pass data from the controller to the view (Thymeleaf template).
model.addAttribute("name", name): Adds the name variable to the model.
model.addAttribute("message", "Hello, " + name + "!"): Adds the message variable to the model.
model.addAttribute("title", "Greeting Page"): Adds the title variable to the model.
return "greeting";: This returns the logical name of the Thymeleaf template file (greeting.html), which Spring will resolve using the configured view resolver.
4. Run Your Spring Boot Application:When you run your Spring Boot application and access the /greeting URL (e.g., http://localhost:8080/greeting or http://localhost:8080/greeting?name=User), Spring MVC will:
Invoke the greeting method in your GreetingController.
Add the specified attributes (name, message, title) to the Model.
Forward the request to the greeting.html template.
Thymeleaf will process greeting.html, replacing the th:text attributes with the values from the Model.
The resulting HTML will be sent back to the client's browser.
This example demonstrates a basic usage of Thymeleaf to display dynamic content based on data passed from a Spring Boot controller. Thymeleaf offers many more powerful features for handling forms, iterating over data, conditional logic, and creating reusable template fragments, making it a versatile choice for building the view layer of your Spring Boot applications.