Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 66 ยท Building REST APIs

Server-Side Views with Thymeleaf

Build HTML pages in Spring Boot with Thymeleaf: models and view names, forms and validation errors, fragments, escaping, and when SSR beats a JSON API.

Not every Spring Boot application is a JSON API for a mobile app or a single-page frontend. Plenty of useful software is simply a set of web pages: an admin panel, an internal tool, a documentation site, a small shop. For those, the server can build the HTML itself and send a finished page to the browser. This is called server-side rendering (SSR), and in the Spring world the most popular template engine for it is Thymeleaf.

This lesson shows the whole round trip: a controller fills a model, returns a view name, and a template turns the model into HTML. You will see forms with validation errors, reusable fragments, and the rule that keeps pages safe from script injection. The deeper tour of the engine lives in Thymeleaf and Spring MVC; here we focus on how Boot wires it up.

The real Spring Boot and Thymeleaf cannot run on this site, so their code is read-only. The runnable examples are stand-ins: a tiny template engine written in plain Java that does the same three jobs (substitute values, escape them, include fragments) so you can watch the idea work.

Model, view name, template

A controller for pages uses @Controller, not @RestController. The difference matters: with @RestController the returned value becomes the response body, but with @Controller a returned String is a view name that Spring looks up.

Java
@Controller
class BookPageController {

    private final BookService bookService;

    BookPageController(BookService bookService) {
        this.bookService = bookService;
    }

    @GetMapping("/books")
    String list(Model model) {
        model.addAttribute("books", bookService.findAll());
        model.addAttribute("title", "All books");
        return "books/list";
    }
}

The Model is a map of named values that the template can read. The returned name books/list is turned into a file path by the Thymeleaf auto-configuration: prefix classpath:/templates/, suffix .html. So the template lives at src/main/resources/templates/books/list.html.

One page request

Request The browser asks for /books.
Model The controller adds data.
View name It returns "books/list".
Template Thymeleaf renders HTML.
1 / 2

The template itself is ordinary HTML with extra th: attributes. Because it is valid HTML, a designer can open it directly in a browser and see placeholder text, which is the main idea behind "natural templates".

HTML
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title th:text="${title}">Page title</title>
</head>
<body>
  <h1 th:text="${title}">Page title</h1>

  <ul>
    <li th:each="book : ${books}">
      <a th:href="@{/books/{id}(id=${book.id})}" th:text="${book.title}">A book</a>
      <span th:if="${book.pages > 500}">(long read)</span>
    </li>
  </ul>
  <p th:if="${#lists.isEmpty(books)}">Nothing here yet.</p>
</body>
</html>
  • ${...} reads a value from the model; *{...} reads from the current form object.
  • th:text replaces the element's text, th:each repeats the element, th:if removes it when false.
  • @{...} builds URLs and adds the application's context path for you.

The first runnable stand-in below does the central job of every template engine: replace placeholders with values from a model. Notice what it does to a title that contains angle brackets.

Java A tiny template engine with escaping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The escaped line is harmless text; the raw line would run a script in a real browser. This is the single most important habit with templates, and it gets its own section below.

Forms, binding and validation errors

A form page needs two controller methods: one that shows the empty form, and one that receives the posted data. The posted fields are bound to an object (a record works well) and checked with the Bean Validation annotations you will meet in Bean Validation.

Java
record BookForm(@NotBlank String title, @Min(1) int pages) {}

@Controller
class BookFormController {

    @GetMapping("/books/new")
    String showForm(Model model) {
        model.addAttribute("form", new BookForm("", 0));
        return "books/form";
    }

    @PostMapping("/books")
    String create(@Valid @ModelAttribute("form") BookForm form,
                  BindingResult result,
                  RedirectAttributes redirect) {
        if (result.hasErrors()) {
            return "books/form";            // show the same page again, with errors
        }
        bookService.create(form);
        redirect.addFlashAttribute("message", "Book saved");
        return "redirect:/books";           // Post/Redirect/Get
    }
}

Three details deserve attention:

  • BindingResult must come directly after the @Valid parameter. Without it, a validation failure throws an exception instead of letting you redisplay the form.
  • On errors you return the form's view name, and the model already holds the submitted values, so the user does not retype everything.
  • On success you redirect rather than render. After a successful POST the browser would otherwise offer to resubmit the form on refresh. Redirect after POST, then GET the result: the Post/Redirect/Get pattern. A flash attribute survives exactly one redirect, which is perfect for a "saved" message.

The form template connects fields to the object:

HTML
<form th:action="@{/books}" th:object="${form}" method="post">
  <label>Title <input type="text" th:field="*{title}"></label>
  <span class="error" th:if="${#fields.hasErrors('title')}" th:errors="*{title}">Title error</span>

  <label>Pages <input type="number" th:field="*{pages}"></label>
  <span class="error" th:if="${#fields.hasErrors('pages')}" th:errors="*{pages}">Pages error</span>

  <button type="submit">Save</button>
</form>

th:field fills the id, name and value attributes for you. With Spring Security on the classpath, th:action also adds the hidden CSRF token, so the form keeps working when protection is on (see CSRF, CORS and Secure Defaults).

An HTML form can only send GET and POST. For other methods Spring offers a hidden _method field, but for page-based apps it is simpler to use POST endpoints such as /books/42/delete and keep the real REST verbs for your JSON API.

Fragments and layouts

Most pages share a header, a footer and a navigation bar. Copying them into every template is the quickest way to end up fixing the same bug twelve times. Thymeleaf solves it with fragments: a named piece of a template that other templates include.

HTML
<!-- templates/fragments/layout.html -->
<header th:fragment="header(heading)">
  <nav>Home | Books | About</nav>
  <h1 th:text="${heading}">Heading</h1>
</header>

<!-- templates/books/list.html -->
<div th:replace="~{fragments/layout :: header('All books')}"></div>

th:replace swaps the element for the fragment; th:insert puts the fragment inside the element. Fragments can take parameters, as above. For a full page frame with a content slot, many teams add the Thymeleaf Layout Dialect or build the frame from two or three fragments.

The next stand-in models the same idea: a map of named fragments, a template that includes them, and a loop over model items. It also renders a form with a validation error, the way th:errors would.

Java Fragments, loops and form errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Every page assembled from the same header and footer fragments stays consistent, and the user's typed values come back in the redisplayed form. In real Thymeleaf the engine reads the fragments from template files and the errors from the BindingResult.

Escaping and safe output

Template engines are the front line against cross-site scripting (XSS). Thymeleaf's th:text and [[...]] inline expressions HTML-escape every value, so <script> shows up as visible text. The unescaped forms, th:utext and [(...)], write the value as raw HTML.

  • Use th:text for everything that comes from users or databases.
  • Use th:utext only for HTML you produced and trust, such as output of a sanitizing library. If you must show user-written rich text, sanitize it on the server first.
  • Escaping depends on context. A value placed inside a <script> block or an onclick attribute needs JavaScript escaping, which Thymeleaf handles with inline mode (th:inline="javascript"), not by hand.

Never build HTML with string concatenation in a controller and return it as a page. You would give up the escaping that the template engine does for free.

When to choose server-side rendering

SSR is not a lesser choice than a JSON API plus a JavaScript frontend; it is a different trade.

  • Good fit: admin tools, internal dashboards, content sites, forms-heavy workflows, teams without a dedicated frontend developer, pages that must work without JavaScript, and anything where fast first paint and simple SEO matter.
  • Weaker fit: highly interactive apps (drag and drop, live editing), apps that must also serve a mobile client from the same endpoints, and teams with an established frontend stack.
  • Middle road: SSR with small doses of JavaScript, for example htmx or Alpine, keeps the server in charge of HTML and still gives snappy partial updates.

You can also mix both in one Boot application: @Controller classes for pages and @RestController classes for JSON, sharing the same services. Just keep the two kinds of controller in separate packages so the difference stays obvious.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A method in a @Controller class returns the string "books/list". What does Spring do with it?

    In a @Controller, a returned String is resolved as a view name. With Thymeleaf it becomes templates/books/list.html. In a @RestController the same string would be the body.
  2. 2. Where must the BindingResult parameter be placed in a handler method with @Valid?

    Spring pairs a BindingResult with the parameter directly before it. If it is missing, a validation failure throws an exception instead of letting you redisplay the form with errors.
  3. 3. Why does a successful form POST usually return redirect:/books instead of rendering the list page?

    This is the Post/Redirect/Get pattern. After the redirect the browser holds a harmless GET request, so refreshing does not resubmit the form.
  4. 4. Which attribute should you use to print a user's comment on a page?

    th:text escapes <, >, & and quotes, which blocks script injection. Use th:utext only for HTML you generated and trust.

Summary

  • Server-side rendering builds HTML on the server; in Boot, add spring-boot-starter-thymeleaf and put templates in src/main/resources/templates.
  • A @Controller fills a Model and returns a view name; a @RestController returns the body itself.
  • Forms bind to an object (a record works), validate with @Valid, and put BindingResult right after it.
  • Redirect after a successful POST (Post/Redirect/Get) and use flash attributes for one-time messages.
  • Fragments (th:fragment, th:replace) remove duplicated headers and footers.
  • th:text escapes output; th:utext does not, so reserve it for trusted HTML.
  • Choose SSR for forms-heavy, content-heavy and internal apps; choose an API plus frontend when interactivity or multiple clients dominate.

Next: File Uploads, Downloads and Static Resources.