Thymeleaf integration with Spring (Part 2)

1 Introduction

This is the second part of the Thymeleaf integration with Spring tutorial. You can read the first part here, where you will learn how to configure this project.

As explained at the beginning of the first part of this tutorial, the web application will send two types of requests:

  • Insert a new guest: Sends a synchronous request to the server for adding a new guest. This will demonstrate how Thymeleaf is integrated with Spring鈥檚 form backing beans.
  • List guests: Sends an AJAX request that will update a region (fragment) of the page in order to show the guest list returned from the server.

Let’s see how we will accomplish this.

2 Handling forms

In this section we are going to see how a form is submitted with Thymeleaf. We will basically need three attributes:


The first two are defined in the form element:

<form id="guestForm" th:action="@{/spring/guests/insert}" th:object="${guest}" method="post">


The th:action attribute rewrites the action url, prefixing the application context to it.

The th:object attribute in the form element is the object selection. It can then be referenced within the form. What we do here is bind the form backing bean to the model attribute, which we defined in the controller before rendering the view:

public Guest prepareGuestModel() {
    return new Guest();


As we see, th:object refers to the Guest form backing bean, while th:field will refer to its properties. 聽Take a look at the form body:

<span class="formSpan">
    <input id="guestId" type="text" th:field="*{id}" required="required"/>
    <br />
    <label for="guestId" th:text="#{}">id:</label>

<span class="formSpan" style="margin-bottom:20px">
    <input id="guestName" type="text" th:field="*{name}" required="required"/>
    <br />
    <label for="guestName" th:text="#{}">name:</label>


What th:field will do is assign the value of its input element to the backing bean property. So, when the user submits the form, all these th:field will set the form backing bean properties.

At the controller, we will receive the Guest instance:

@RequestMapping(value = "/guests/insert", method = RequestMethod.POST)
public String insertGuest(Guest newGuest, Model model) {
    return showHome(model);


Now the guest can be inserted into the database.

3 Sending AJAX requests

When trying to find a simple example of sending an AJAX request with Thymeleaf, I have found examples with Spring Webflow (render fragments). I also read others saying that you need Tiles in order to accomplish that.

I didn’t want to use those frameworks so in this section I’m using jQuery to send an AJAX request to the server, wait for the response and partially update the view (fragment rendering).

The form

    <span class="subtitle">Guest list form</span>
    <div class="listBlock">
        <div class="search-block">
            <input type="text" id="searchSurname" name="searchSurname"/>
            <br />
            <label for="searchSurname" th:text="#{search.label}">Search label:</label>
            <button id="searchButton" name="searchButton" onclick="retrieveGuests()" type="button" 
                    th:text="#{search.button}">Search button</button>
        <!-- Results block -->
        <div id="resultsBlock">

This form contains an input text with a search string (searchSurname) that will be sent to the server. There’s also a region (resultsBlock div) which will be updated with the response received from the server.

Guests list form


When the user clicks the button, the retrieveGuests() function will be invoked.

function retrieveGuests() {
    var url = '/th-spring-integration/spring/guests';
    if ($('#searchSurname').val() != '') {
        url = url + '/' + $('#searchSurname').val();


The jQuery load function makes a request to the server at the specified url and places the returned HTML into the specified element (resultsBlock div).

If the user enters a search string, it will search for all guests with the specified surname. Otherwise, it will return the complete guest list. These two requests will reach the following controller request mappings:

@RequestMapping(value = "/guests/{surname}", method = RequestMethod.GET)
public String showGuestList(Model model, @PathVariable("surname") String surname) {
    model.addAttribute("guests", hotelService.getGuestsList(surname));
    return "results :: resultsList";

@RequestMapping(value = "/guests", method = RequestMethod.GET)
public String showGuestList(Model model) {
    model.addAttribute("guests", hotelService.getGuestsList());
    return "results :: resultsList";


The results list

Since Spring is integrated with Thymeleaf, it will now be able to return fragments of HTML. In the above example, the return string “results :: resultsList” is referring to a fragment named resultsList which is located in the results page. Let’s take a look at this results page:

<!DOCTYPE html>
<html xmlns=""
    xmlns:th="" lang="en">


    <div th:fragment="resultsList" th:unless="${#lists.isEmpty(guests)}" class="results-block">
                    <th th:text="#{}">Id</th>
                    <th th:text="#{results.guest.surname}">Surname</th>
                    <th th:text="#{}">Name</th>
                    <th th:text="#{}">Country</th>
                <tr th:each="guest : ${guests}">
                    <td th:text="${}">id</td>
                    <td th:text="${guest.surname}">surname</td>
                    <td th:text="${}">name</td>
                    <td th:text="${}">country</td>


The fragment, which is a table with registered guests, will be inserted in the results block:

Thymeleaf integration with Spring - Part 2. Results page


4 Conclusion

After integrating both frameworks, we learnt how forms are linked to the Spring MVC model. We also learnt how to send AJAX requests and partially update the view.

I’m publishing my new posts on Google plus and Twitter. Follow me if you want to be updated with new content.


22 thoughts on “Thymeleaf integration with Spring (Part 2)

  1. Many thanks for this post ! I wanted to perform AJAX without using webflow or tiles, and never found a correct sample… until now 馃檪

  2. Xavier,

    In the home.html template you have the guestForm action set to:

    I can see the correlation between /guests/insert with the RequestMapping annotation on the insertGuest method of the HomeController, but I'm not understanding the need for the "/spring" portion of the path. It doesn't match anything in the HomeController, your java package structure or path to the HTML. Could you please clarify how the "/spring" is used?


  3. Hello,

    This is the servlet mapping. Since this application is integrated with Spring, its servlet will handle the request. You can take a look at web.xml and you will see that the Spring servlet's mapping is "/spring/*"

  4. Hi Xavier, thanks for the excellent post! By far the most informative when it comes to Spring / Thymeleaf integration I came across. If your project is open sourced, would you mind publishing the sample project in Github? It will be helpful to see the project in whole to understand components.

  5. Hi Xavier!
    I think it's not correct to present url in var url = '/th-spring-integration/spring/guests';
    Because it is context dependent. I guess more correct define it as
    var url = '@{/spring/guests}'; and add th:inline="javascript" to the "script" section.

    Regargds, Alexander

  6. Hola Xavier,

    Two thinks:

    To view all list at the begining I add a window.load = retrieveGuests(). Is there any better way to do it?

    Do you know any example with a page/size/sort options?
    In my code (spring boot/thymeleaf) I use a spring:
    PageableHandlerMethodArgumentResolver, SortHandlerMethodArgumentResolver beans
    and Pageable/page/pagRequest class.

    My list controller:
    public String listForm(Model model, @RequestParam String search,
    @PageableDefault Pageable pageable, @SortDefault Sort sort)

    Page page = search(search, pageable); (call to service/repository)
    model.addAttribute("page", page);
    return "/list";

    In my list.html (Thymeleaf) you can change the page, page size and sort of result list, and refresh by calling the url:
    th:ref=@{/list(search=${term},page=${page},size=${size},sort=${sort})} (not tested) => /list?search=whatever?page=1?size=20?sort=createDt,asc

    I want to migrate it to ajax, and I found your awesome example, but I don't know how to change it so I can manage the search/page/size/sort parameters.(mainly the javascript code).


Leave a Reply

Your email address will not be published. Required fields are marked *