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

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

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

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

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

<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.

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Subscribe to RSS Feed.

👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, Buy me a coffee (cost $3) .

Need help to launch a new product? I am available for contract work. Hire me to accomplish your business goals with engineering and design.