Thymeleaf is a popular server-side template engine for Java applications. You can easily integrate it into a Spring Boot project to develop web applications.

In a standard Spring MVC application, the controller classes are the ones that collect data from different sources like databases or RESTful APIs and then select a view to render and return the HTML back to the user. They create a model map with data, later converted into a Thymeleaf context object.

In this article, you'll learn how to access Spring model attributes, request parameters, session attributes, and Spring beans in Thymeleaf templates.

Spring Model Attributes

Spring model attributes transfer data from Spring controllers to Thymeleaf views. In Thymeleaf terminology, they are called context variables.

There are several ways to add model attributes to a view in Spring MVC. The simplest way is to use the Model's addAttribute() method:

@GetMapping("/todos")
public String todoList(Model model) {

    List<Todo> todos = Arrays.asList(
            new Todo(1, "Buy milk"),
            new Todo(2, "Prepare Java talk"),
            new Todo(3, "Go for a walk")
    );

    // add model attribute
    model.addAttribute("todos", todos);

    return "index";
}

Alternatively, you could also return a ModelAndView object with model attributes included:

@GetMapping("/todos")
public ModelAndView todoList() {

    List<Todo> todos = Arrays.asList(
            new Todo(1, "Buy milk"),
            new Todo(2, "Prepare presentation"),
            new Todo(3, "Write tutorial")
    );

    // create a new `ModelAndView` object
    ModelAndView mav = new ModelAndView("index");
    mav.addObject("todos", todos);

    return mav;
}

You can also use the @ModelAttribute annotation to expose common model attributes:

@ModelAttribute
public List<Todo> todos() {
    return Arrays.asList(
            new Todo(1, "Buy milk"),
            new Todo(2, "Prepare presentation"),
            new Todo(3, "Write tutorial")
    );
}

As you can see in the above examples, we are adding the todos attribute to the model. It will be available in Thymeleaf views as a context variable.

In Thymeleaf templates, you can use Spring Expression Language (SpEL) to access context attributes. For example, the above todos context variable is accessible by using the ${todos} SpEL expression in a Thymeleaf view:

<ul th:each="todo: ${todos}">
    <li th:text="${todo.id + ': ' + todo.title}"></li>
</ul>

Request Parameters

Request parameters (also called query string parameters) are passed from the client to the server as part of the URL:

https://google.com/search?q=thymeleaf&lang=en&num=15

To access query string parameters in a Thymeleaf template, you can use the param prefix as shown below:

<div th:text="${param.q}">search query</div>
<div th:text="${param.lang}">language</div>
<div th:text="${param.num}">results per page</div>

If the parameter is not present, Thymeleaf doesn't throw an exception. Instead, an empty string is displayed.

Since the request parameters can be multi-valued (http://example.com?size=M&size=L), you can also use bracket syntax to access them:

<div th:text="${param.size[0] + ' ' + param.size[1]}">sizes</div>

Read this guide to learn more about accessing query string parameters in Thymeleaf.

Session Attributes

Spring MVC uses the HttpSession class for the session management and storing any temporary information:

@GetMapping("/signup")
public String signup(HttpSession session) {

    // store data in session
    session.setAttribute("email", "john.doe@example.com");

    return "signup";
}

You can use the session. prefix to access any data stored in the current session:

<div th:text="${session.email}">User email

You could also use #session that would give you direct access to the javax.servlet.http.HttpSession object in a Thymeleaf template:

<div th:text="${#session.getAttribute('email')}">User email</div>

To learn more about accessing session attributes in Thymeleaf, read this article.

Spring Beans

Thymeleaf allows us to access beans registered at the Spring Application Context using the @beanName syntax.

Let us create a simple Spring bean and register it with the Application Context:

@Configuration
public class ThymeleafConfig {
    @Bean(name = "googleSearch")
    public GoogleSearch googleSearch() {
        return (q) -> "https://google.com/search?q=" + q;
    }
}

public interface GoogleSearch {
  String buildUrl(String q);
}

Now you can use the GoogleSearch beans by using @googleSearch in a Thymeleaf template:

<a th:href="${@googleSearch.buildUrl('Choco Milk')}">Choco Milk</a>

To learn more about Thymeleaf and how to use it in a Spring Boot application, check out this article.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.