REST APIs return raw data, but many applications also need to serve complete web pages that a browser can display directly. Thymeleaf is a template engine bundled with Spring Boot that builds HTML pages by combining a template file with data supplied from a controller, without needing a separate front-end framework.

Add the dependency

Including spring-boot-starter-thymeleaf in the project is enough to enable it. Once present, Spring Boot automatically looks for template files inside src/main/resources/templates and serves them when a controller returns a matching name.

A controller that returns a page

A page-rendering controller uses @Controller rather than @RestController, because its methods should return the name of a template rather than raw data. Values are passed to the template through a Model object:

@Controller
public class HomeController {
  @GetMapping("/")
  public String home(Model model) {
    model.addAttribute("name", "World");
    return "home";
  }
}

The template

Create home.html inside the templates folder. Thymeleaf attributes, all prefixed with th:, fill placeholders with real data when the page is rendered:

<h1 th:text="'Hello ' + ${name}">Hello</h1>

The th:text attribute replaces the tag's normal content with the given expression once rendered, so a browser viewing the page sees "Hello World" instead of the placeholder text "Hello" that appears only if the file is opened directly without Thymeleaf processing it.

Conditionals and loops

Two attributes cover most everyday templating needs. th:if only renders an element when a condition is true:

<p th:if="${user != null}">Welcome back!</p>

th:each repeats an element once per item in a collection:

<li th:each="item : ${items}" th:text="${item}"></li>

Linking to static resources and other pages

Thymeleaf provides a special link syntax, @{...}, that correctly builds application-relative URLs for stylesheets, scripts and links, which matters once the app is deployed somewhere other than localhost:

<link th:href="@{/css/site.css}" rel="stylesheet">
<a th:href="@{/products}">See products</a>

REST APIs versus server-rendered pages

It is worth being clear about when to reach for Thymeleaf rather than a REST endpoint. A REST API, built with @RestController, suits a mobile app or a separate JavaScript front end that wants raw data. Thymeleaf suits an application where the server itself produces the finished HTML that a browser displays, which remains a simple and effective choice for content-focused sites, admin panels and traditional multi-page web applications.