Creating Your First “Hello World” Web Page with Thymeleaf and Spring Boot
Thymeleaf is a powerful template engine that integrates seamlessly with Spring Boot to help you build dynamic web applications. Let’s walk through, step by step, how to create a simple web page that displays a static message using Thymeleaf, with a Spring Boot controller that serves this page—aka the classic “Hello World” example.
1. Project Setup
You’ll need:
- Java (version 8+)
- Maven or Gradle
- Spring Boot (with the Thymeleaf starter)
Quick start with Spring Initializr:
- Go to https://start.spring.io (or use your IDE's Spring initializer)
- Choose Maven/Gradle, Java version, and add dependencies:
Spring Web
andThymeleaf
- Generate and unzip your new project folder
2. Add Thymeleaf Template
Create a folder named templates
under src/main/resources
. Inside it, add a file named greeting.html
:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Hello Thymeleaf</title> </head> <body> <h1 th:text="'Hello, Thymeleaf World!'">Hello fallback</h1> </body> </html>
After your </html>
tag, you may add a <br>
if you want a blank line after the rendered content, but that isn't necessary for this example.
3. Write the Spring Controller
Create a controller class in src/main/java/com/example/demo
(or your package):
package com.example.demo; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class GreetingController { @GetMapping("/greet") public String sayHello() { // Return the name of the Thymeleaf template (without .html) return "greeting"; } }
4. Run the Application
Open a terminal in your project directory.
- If using Maven, run:
./mvnw spring-boot:run
- If using Gradle, run:
./gradlew bootRun
Open your browser and navigate to: http://localhost:8080/greet
You should see:
Hello, Thymeleaf World!
5. How It Works
- The controller method
/greet
returns the Thymeleaf view named"greeting"
. - Thymeleaf, integrated in Spring Boot, automatically resolves the
greeting.html
template in/resources/templates/
. - The static message is set using
th:text
, but you could easily swap in a dynamic value from the backend.
6. Making the Message Dynamic (Optional)
Controller:
@GetMapping("/greet") public String sayHello(Model model) { model.addAttribute("message", "Hello, Dynamic Thymeleaf!"); return "greeting"; }
Template:
<h1 th:text="${message}">Hello fallback</h1>
7. Summary
This “Hello World” project demonstrates how easy it is to wire up a Spring Boot controller to serve a Thymeleaf HTML template with just a few lines of code. You can now build on this foundation to create dynamic, data-driven web pages and rich user interfaces.