How to get session attributes in Thymeleaf

In this article 👇

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 me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.