Skip to content
Tutorials Center
My learning

Topics

Lesson 85 of 119 ยท Spring Boot

Server-side Views with Thymeleaf

Render HTML on the server with Thymeleaf and Spring MVC, from th:text and th:each to form binding and validation, fragments, the post-redirect-get pattern and XSS-safe output.

Not every web application needs a JavaScript front end. Admin tools, internal dashboards, documentation sites and plenty of public websites are happy with the classic approach: the server builds the complete HTML page for every request and the browser just displays it. The result is simple to deploy, works without JavaScript, is easy for search engines to read and keeps your logic in one language.

In Spring applications the most popular tool for this is Thymeleaf, a template engine that is built for HTML. Where JSP mixes Java-like tags into the markup, a Thymeleaf template is a real HTML file: you add th: attributes to ordinary tags, and the file still opens correctly in a browser even without a server. This lesson shows how a template engine works by building a tiny one, then covers the real thing in Spring MVC: expressions, loops, forms with validation, fragments and the safety rules. You should know Spring MVC and validation.

How a view gets rendered

In Spring MVC a controller method does not write HTML. It fills a model (a map of names to values) and returns the name of a view. Spring Boot's Thymeleaf auto-configuration then finds src/main/resources/templates/<name>.html, merges the model into it and sends the result.

sequenceDiagram
  participant B as Browser
  participant D as DispatcherServlet
  participant C as Controller
  participant T as Thymeleaf engine
  B->>D: GET /books
  D->>C: books(model)
  C-->>D: model has "books", returns view name "books/list"
  D->>T: render templates/books/list.html with the model
  T-->>B: finished HTML page

The controller chooses data and a view name; the template engine turns both into HTML.

Add the starter spring-boot-starter-thymeleaf and write:

Java
@Controller
class BookPageController {

    private final BookService books;

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

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

Note @Controller, not @RestController: the return value is a view name, not a response body.

A mini template engine

The core idea of Thymeleaf is small: find elements with th: attributes, evaluate their expressions against the model, and replace the element's content. The example below implements th:text, th:utext, th:if, th:each and th:replace for one-line elements. Real Thymeleaf has a full parser and a much richer expression language, but you will recognize every behavior in the output:

Java A tiny Thymeleaf-style engine

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.

Look at the second book. th:text turned <i>Emma</i> & friends into harmless text (&lt;i&gt;), so a user cannot inject markup through a title. th:utext (unescaped text) inserted the notice as raw HTML, which is exactly what you want for trusted markup and exactly what you must never do with user input. Also notice that every th: attribute vanished from the output, while the placeholder text (Sample title) was replaced: the template works as a static prototype too, which designers appreciate. Thymeleaf calls this natural templating.

Thymeleaf expressions

Thymeleaf has several expression types, each with its own delimiter:

Syntax Meaning Example
${...} Variable from the model (Spring EL) th:text="${book.title}"
*{...} Property of the object selected with th:object th:field="*{title}"
#{...} Text from messages.properties (i18n) th:text="#{books.heading}"
@{...} URL, with context path and parameters th:href="@{/books/{id}(id=${book.id})}"
~{...} Fragment reference th:replace="~{layout :: header}"

The ${...} language is the Spring Expression Language, so ${books.size()}, ${book.year > 2000 ? 'new' : 'old'} and ${#lists.isEmpty(books)} all work. Utility objects such as #temporals, #numbers and #strings format values: th:text="${#temporals.format(order.createdAt, 'dd MMM yyyy')}".

Conditions and loops use attributes on the elements themselves:

HTML
<table th:if="${!books.isEmpty()}">
  <tr th:each="book, status : ${books}" th:classappend="${status.odd} ? 'striped'">
    <td th:text="${status.count}">1</td>
    <td><a th:href="@{/books/{id}(id=${book.id})}" th:text="${book.title}">Title</a></td>
    <td th:text="${book.year}">2000</td>
  </tr>
</table>
<p th:unless="${!books.isEmpty()}">Nothing here yet.</p>

The optional second variable in th:each is a status object with index, count, first, last, odd and even. Use @{...} for every internal link: it adds the application's context path and URL-encodes parameters.

Forms, validation and Post-Redirect-Get

Thymeleaf binds forms to objects. The controller puts a form object in the model, the template uses th:object and th:field, and on submit Spring fills the object, runs Bean Validation and hands you a BindingResult:

Java
record BookForm(@NotBlank @Size(max = 60) String title,
                @NotNull @Min(1450) Integer year) {}

@Controller
@RequestMapping("/books/new")
class BookFormController {

    private final BookService books;

    BookFormController(BookService books) { this.books = books; }

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

    @PostMapping
    String submit(@Valid @ModelAttribute BookForm bookForm, BindingResult errors,
                  RedirectAttributes redirect) {
        if (errors.hasErrors()) {
            return "books/form";                         // show the page again with messages
        }
        books.create(bookForm.title(), bookForm.year());
        redirect.addFlashAttribute("message", "Book saved");
        return "redirect:/books";                        // 303 to a GET
    }
}
HTML
<form th:action="@{/books/new}" th:object="${bookForm}" 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>Year <input type="number" th:field="*{year}"></label>
  <span class="error" th:if="${#fields.hasErrors('year')}" th:errors="*{year}">Year error</span>

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

th:field generates the id, name and value attributes, so after a failed submit the user's input is still in the fields. With Spring Security enabled, th:action also adds the hidden CSRF token automatically, a good reason to prefer it over a plain action (Web Security Basics).

Notice the two different endings of submit. After a failed validation the controller renders the form directly. After a successful save it redirects. This is the Post-Redirect-Get pattern:

flowchart TD
  A["Browser: POST /books/new"] --> B{"Valid?"}
  B -->|"no"| C["200: render form again with errors"]
  B -->|"yes"| D["Save the book"]
  D --> E["303 See Other: /books"]
  E --> F["Browser: GET /books"]
  F --> G["200: list page with flash message"]

Redirecting after a successful POST means that pressing reload repeats the harmless GET, not the save.

Without the redirect, reloading the success page would resubmit the form and create a duplicate book. A flash attribute survives exactly one redirect, which is how the "Book saved" message gets from the POST to the next page. The simulation below runs the same flow with an escaping renderer, including a hostile input:

Java Post-Redirect-Get with validation

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 hostile title is stored and later shown as text, not as an attribute injection, because every value passed through escape. Thymeleaf's th:field and th:text do this for you.

Fragments and layouts

Pages share a header, footer and navigation. Define a fragment once and reuse it:

HTML
<!-- templates/fragments/layout.html -->
<header th:fragment="siteHeader(active)">
  <nav>
    <a th:href="@{/}" th:classappend="${active == 'home'} ? 'current'">Home</a>
    <a th:href="@{/books}" th:classappend="${active == 'books'} ? 'current'">Books</a>
  </nav>
</header>
HTML
<!-- templates/books/list.html -->
<div th:replace="~{fragments/layout :: siteHeader('books')}"></div>

th:replace swaps the element for the fragment, while th:insert puts the fragment inside it. Fragments can take parameters, so one <head> fragment can set each page's title. For full page layouts people either pass the page body as a fragment parameter, or use the Thymeleaf Layout Dialect, which adds layout:decorate.

Working safely and productively

  • Keep th:text as the default. Use th:utext only for HTML you generated yourself or sanitized.
  • Inside JavaScript, use th:inline="javascript" so Thymeleaf serializes values correctly; never paste model values into script text by hand.
  • Set spring.thymeleaf.cache=false while developing so edits show without a restart, and leave caching on in production.
  • Do not call repositories from templates. Prepare everything in the controller and keep templates free of logic beyond display.
  • Test pages with MockMvc: mockMvc.perform(get("/books")).andExpect(content().string(containsString("Dune"))), as in Spring Boot Testing.
  • For a mix of pages and JSON, use @Controller classes for pages and @RestController classes for the API; both can share the same services.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A controller annotated with @Controller returns the String "books/list". What happens?

    With @Controller a returned String is a view name. With @RestController (or @ResponseBody) it would be the body.
  2. 2. What is the difference between th:text and th:utext?

    Escaping prevents cross-site scripting. Use utext only for trusted markup.
  3. 3. Why does a controller return "redirect:/books" after a successful form POST?

    This is the Post-Redirect-Get pattern. It prevents duplicate submissions.
  4. 4. Which expression builds a link that respects the application's context path?

    @{...} is the link expression. $ is a variable, # a message key and ~ a fragment.
  5. 5. What does a flash attribute do?

    Flash attributes are kept temporarily (in the session) and removed after the redirected request.

Summary

  • Thymeleaf renders HTML from templates plus a model; controllers return a view name and fill the model.
  • Templates are valid HTML with th: attributes: th:text, th:if, th:each, th:href, th:replace. th:text escapes, th:utext does not.
  • Expressions: ${} variables, *{} selected object, #{} messages, @{} URLs, ~{} fragments.
  • Forms use th:object, th:field and th:errors with @Valid and BindingResult; redirect after a successful POST and use flash attributes for messages.
  • Fragments remove duplicated headers and layouts; keep logic out of templates and caching on in production.

Next: Caching and Data with Redis speeds up your pages and APIs with an in-memory data store.