14

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555

2 Answers2

29

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

erhun
  • 3,549
  • 2
  • 35
  • 44
Rafal Borowiec
  • 5,124
  • 1
  • 24
  • 20
  • hello, is it possible to access currently logged in user via this `session` object? mainly for use in a `th:if` statement, maybe like: `
    `?
    – Scaramouche Oct 09 '18 at 05:00
  • @Scaramouche you can but you have to put the bracelet after joe: th:if="${session.user.username == 'joe'}" – leachim May 27 '20 at 08:12
1

I tried this and it's working for me :

th:text="${session.user['tel']}"
Abd Abughazaleh
  • 4,615
  • 3
  • 44
  • 53