Accessing session attributes in Thymeleaf templates
Asked Answered
C

2

15

I would like to know whether is it possile to retrieve the session object and access its attributes from a Thymeleaf template without any controller code.

Condescendence answered 17/12, 2013 at 10:49 Comment(0)
D
31

In Thymeleaf, session object can be easily accessed in a template:

  • with a session variable:
    ${session.foo} // Retrieves the session atttribute 'foo'
    ${session.size()}
    ${session.isEmpty()}
    ${session.containsKey('foo')}
  • with a #ctx object:
    ${#ctx.httpSession}

Look at the Thymeleaf documentation for accessing different context objects: http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#expression-basic-objects

Doctrinaire answered 1/3, 2014 at 21:8 Comment(2)
hello, is it possible to access currently logged in user via this session object? mainly for use in a th:if statement, maybe like: <div th:if="${session.user.username} == 'joe'"></div>?Epiblast
@Epiblast you can but you have to put the bracelet after joe: th:if="${session.user.username == 'joe'}"Nebula
L
1

I tried this and it's working for me :

th:text="${session.user['tel']}"
Lemma answered 1/8, 2021 at 14:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.