# How to get session attributes in Thymeleaf

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Jan 29, 2020. Topics: Thymeleaf.
Canonical URL: https://attacomsian.com/blog/thymeleaf-get-session-attributes

> A quick guide to learn how to access session attributes in Thymeleaf templates.

[Thymeleaf](https://attacomsian.com/blog/spring-boot-thymeleaf-example) is a modern server-side template engine for Java-based web applications. In this article, you'll **learn how to access data from session** in Thymeleaf templates.

## Using `session` Object

Let us say we have the following controller method that stores a variable in the `HttpSession` object:

```java
@GetMapping("/login")
public String loginPage(HttpSession session) {

    // store data in session
    session.setAttribute("name", "Atta");

    return "login";
}
```

To **access** the above attribute from session in a Thymeleaf template, you can use the `session` object as shown below:

```markup
<div th:text="${session.name}">John Doe</div>
```

`${session.name}` will return the value of the `name` attribute stored in the current session. If **no attribute** with the specified name is found in the session, it will return `null`. 

To **check if an attribute exists** in session, you can simply use the `session.containsKey()` method as shown below:

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

You can also use `session` to get the **number of attributes** stored in the session as well as to check if the **session is empty**:

```markup
<p>
    Total objects stored in current session are
    <th:block th:text="${session.size()}">0</th:block>.
</p>

<p>
    Is session empty?
    <th:block th:text="${session.isEmpty()} ? 'Yes' : 'No'">Yes</th:block>
</p>
```

To get **direct access** to the `javax.servlet.http.HttpSession` object in Thymeleaf views, just append `#` before `session` as shown below:

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

## Conclusion

In this quick article, we looked at different ways to access session attributes in Thymeleaf templates. You can use the `session` object to easily access any attribute stored in the current session.
