Hello World with Thymeleaf
Time to build your first Thymeleaf page. We'll create a simple "Hello World" app with a controller and a template. Let's understand this step by step.
The Template
Create a file called hello.html inside src/main/resources/templates/.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Hello World</title>
</head>
<body>
<h1 th:text="${message}">Hello!</h1>
</body>
</html>
The xmlns:th declaration tells Thymeleaf to process the th: attributes. Without it, Thymeleaf ignores everything.
The Controller
Now create a Spring Boot controller that returns the view name and passes data to the model.
@Controller
public class HelloController {
@GetMapping("/hello")
public String sayHello(Model model) {
model.addAttribute("message", "Hello, Thymeleaf!");
return "hello";
}
}
The @GetMapping("/hello") maps the URL. model.addAttribute puts data into the template. The return value "hello" tells Spring to look for hello.html in the templates folder.
Run the App
Start your Spring Boot application and visit http://localhost:8080/hello. You should see "Hello, Thymeleaf!" on the page.
If you see it, congratulations — your first Thymeleaf template is working! That's all there is to it. Controller, template, done.