Integrating Thymeleaf with Spring Boot

 Integrating Thymeleaf with Spring Boot is straightforward since Spring Boot provides built-in support for Thymeleaf. Here's a step-by-step guide to help you integrate Thymeleaf with a Spring Boot application:



✅ Step 1: Create a Spring Boot Project
You can create a Spring Boot project using:

Spring Initializr
Your IDE (IntelliJ IDEA, Eclipse, etc.)
Select the following dependencies:

Spring Web
Thymeleaf
(Optionally: Spring Boot DevTools for hot reloading)

✅ Step 2: Project Structure
Your project should look something like this:

src
├── main
│ ├── java
│ │ └── com.example.demo
│ │ └── DemoApplication.java
│ └── resources
│ ├── static
│ ├── templates
│ │ └── index.html
│ └── application.properties


✅ Step 3: Add Thymeleaf Dependency (if not already added)
If you didn't use Spring Initializr, add the dependency manually to your pom.xml:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Or for Gradle:

implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'


✅ Step 4: Create a Controller
package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

@GetMapping("/")
public String index(Model model) {
model.addAttribute("message", "Hello from Spring Boot and Thymeleaf!");
return "index"; // Refers to templates/index.html
}
}


✅ Step 5: Create a Thymeleaf Template
Create src/main/resources/templates/index.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf + Spring Boot</title>
</head>
<body>
<h1 th:text="${message}">Placeholder message</h1>
</body>
</html>


✅ Step 6: Run the Application
Run the application with:

./mvnw spring-boot:run

or from your IDE. Open your browser and go to http://localhost:8080/.


✅ Optional: Configure Thymeleaf Settings
In application.properties (optional tweaks):

spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html


๐Ÿ“Œ Notes:
Thymeleaf templates are placed in the /resources/templates directory by default.
Static files (CSS/JS/images) go in /resources/static.
Thymeleaf expressions: th:text, th:each, th:if, etc.

Comments

Popular posts from this blog

How to Install and Set Up Selenium in Python (Step-by-Step)

Tosca for API Testing: A Step-by-Step Tutorial

Waits in Playwright: Explicit, Implicit, and Auto