Introduction

Spring Boot offers powerful tools for building web applications, and the combination of Spring Boot's Model-View-Controller (MVC) framework with the Thymeleaf templating engine makes it easy to create dynamic and responsive web pages. In this guide, we'll explore how to work with Spring Boot MVC and Thymeleaf, complete with sample code and examples.


Prerequisites

Before you start, make sure you have the following prerequisites:


Setting Up the Project

Let's start by creating a Spring Boot project that includes the necessary dependencies for Spring Boot MVC and Thymeleaf. You can do this through the Spring Initializr or by adding the dependencies to your pom.xml (if using Maven) or build.gradle (if using Gradle).

Example pom.xml for Maven:

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

With these dependencies in place, you're ready to start working with Spring Boot MVC and Thymeleaf.


Creating a Controller

In Spring Boot, controllers are responsible for handling HTTP requests and returning responses. Let's create a simple controller to handle requests:

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class MyController {
@GetMapping("/hello")
public String hello(Model model) {
model.addAttribute("message", "Hello, Spring Boot and Thymeleaf!");
return "hello";
}
}

This controller responds to requests to /hello and returns a Thymeleaf view named "hello." It also adds a "message" attribute to the model, which can be displayed in the view.


Creating a Thymeleaf Template

Thymeleaf is a templating engine that allows you to create dynamic HTML pages. Create a Thymeleaf template named "hello.html" in your project's src/main/resources/templates directory:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Hello Page</title>
</head>
<body>
<h1>Thymeleaf Example</h1>
<p th:text="${message}">Message goes here</p>
</body>
</html>

The th:text attribute is a Thymeleaf expression that displays the "message" attribute from the controller's model.


Running the Application

Now that you have a controller and a Thymeleaf template, you can run your Spring Boot application. Access http://localhost:8080/hello in your web browser, and you should see the "Hello, Spring Boot and Thymeleaf!" message.


Conclusion

Working with Spring Boot MVC and Thymeleaf allows you to create dynamic web applications with ease. This guide covered the basic setup of a Spring Boot project, creating a controller, and using Thymeleaf templates to display dynamic content. You can now expand on this foundation to build more complex and interactive web applications.