We’ll create a Spring Boot app that:
- Maps a URL
/hello
- Passes a dynamic user name
- Displays it using Thymeleaf template
🔵 1. Project Setup
✅ Maven dependencies in pom.xml
:
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Starter Thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
✅ These two starters are enough!
🔵 2. Create the Main Application Class
File: src/main/java/com/example/demo/DemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
✅ This starts your Spring Boot app.
🔵 3. Create a Controller
File: src/main/java/com/example/demo/controller/HelloController.java
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HelloController {
@GetMapping("/hello")
public String sayHello(Model model) {
model.addAttribute("username", "Stanley");
return "hello"; // Return the template name (hello.html)
}
}
✅ This controller:
- Handles GET request to
/hello
- Adds a
username
attribute into the model - Returns the view
hello.html
🔵 4. Create a Thymeleaf Template
File: src/main/resources/templates/hello.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Hello Page</title>
</head>
<body>
<h1 th:text="'Hello, ' + ${username} + '!'">Hello, Guest!</h1>
</body>
</html>
✅ Here:
th:text
dynamically replaces the content of<h1>
at runtime.- If
username = "Stanley"
, the browser will see:
<h1>Hello, Stanley!</h1>
🔵 5. Run the Application
✅ Run DemoApplication.java
(main()
method).
Open your browser and go to:
http://localhost:8080/hello
You will see:
Hello, Stanley!
🎉 Congratulations! You have a working Spring Boot + Thymeleaf mini project!
🎯 Quick Full Architecture Overview
Layer | Code |
---|---|
Controller | HelloController.java (handles /hello request) |
Template Engine | Thymeleaf (renders hello.html ) |
View (HTML page) | hello.html uses ${username} |
📢 Important Extras:
- Thymeleaf templates must be placed inside
src/main/resources/templates/
. - Thymeleaf automatically resolves
.html
files — you don’t need to add.html
in the controller (return "hello"
not"hello.html"
). - Thymeleaf provides many more features: loops (
th:each
), conditionals (th:if
), fragment reuse (th:fragment
), etc.