# How to access data in Thymeleaf templates

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Jul 15, 2020, updated Sep 24, 2022. Topics: Spring Boot, Thymeleaf.
Canonical URL: https://attacomsian.com/blog/thymeleaf-access-data

> Learn how to access Spring model attributes, request parameters, session attributes, and Spring beans in Thymeleaf templates.

[Thymeleaf](https://attacomsian.com/blog/spring-boot-thymeleaf-example) 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:

```java
@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:

```java
@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:

```java
@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:

```javascript
<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:

```javascript
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:

```markup
<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:

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

Read [this guide](https://attacomsian.com/blog/thymeleaf-get-query-string-parameters) 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:

```java
@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: 

```markup
<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:

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

To learn more about accessing session attributes in Thymeleaf, read [this article](https://attacomsian.com/blog/thymeleaf-get-session-attributes).

## 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:

```java
@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:

```markup
<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](https://attacomsian.com/blog/spring-boot-thymeleaf-example).
