Search code examples
springspring-mvcsessionthymeleafhttpsession

Thymeleaf expression objects: #session and ${session....}


There are two ways to obtain a session attribute in Thymeleaf:

  1. ${#session.getAttribute('attr')}
  2. ${session.attr}

What is the difference between both session "objects"? Is there a situation in which one would work and not the other?


Solution

  • #session usage only works in Web Context ie. it is a helper to directly access to the javax.servlet.http.HttpSession object associated with the current request. This is clearly stated in documentation. So you are directly accessing the Context object here not the variable that is defined by the thymeleaf.

    $session is a shortcut for accessing session attributes. This is not a context object, but it is a map added to the context as a variable, which is added by thymeleaf explicitly. You can find the relevant information here.