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):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
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):
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="${title}"></title>
</head>
<body>
<h1 th:text="${message}"></h1>
</body>
</html>
-
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<title>tag with the value of thetitlevariable passed from the Spring controller. -
th:text="${message}": Similarly, this replaces the content of the<h1>tag with the value of themessagevariable.
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
}
}
-
@Controller: This annotation marks the class as a Spring MVC controller. -
@GetMapping("/greeting"): This maps HTTP GET requests to the/greetingpath to thegreetingmethod. -
@RequestParam: This extracts thenamerequest parameter from the URL. It's optional and defaults to "World". -
Model model: Spring'sModelobject is used to pass data from the controller to the view (Thymeleaf template). -
model.addAttribute("name", name): Adds thenamevariable to the model. -
model.addAttribute("message", "Hello, " + name + "!"): Adds themessagevariable to the model. -
model.addAttribute("title", "Greeting Page"): Adds thetitlevariable 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
greetingmethod in yourGreetingController. - Add the specified attributes (
name,message,title) to theModel. - Forward the request to the
greeting.htmltemplate. - Thymeleaf will process
greeting.html, replacing theth:textattributes with the values from theModel. - 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.
Top comments (0)