【问题标题】:Accessing session attributes in Thymeleaf templates访问 Thymeleaf 模板中的会话属性
【发布时间】:2014-01-05 02:18:11
【问题描述】:

我想知道是否可以在没有任何控制器代码的情况下从 Thymeleaf 模板中检索会话对象并访问其属性。

【问题讨论】:

    标签: spring session-variables thymeleaf


    【解决方案1】:

    在 Thymeleaf 中,可以在模板中轻松访问会话对象:

    • 带有session 变量:
    ${session.foo} // 获取会话属性 'foo' ${session.size()} ${session.isEmpty()} ${session.containsKey('foo')}
    • 带有#ctx 对象:
    ${#ctx.httpSession}

    查看访问不同上下文对象的 Thymeleaf 文档:http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#expression-basic-objects

    【讨论】:

    • 你好,是否可以通过session 对象访问当前登录的用户?主要用于th:if 语句,可能像:<div th:if="${session.user.username} == 'joe'"></div>?
    • @Scaramouche 你可以,但你必须把手镯放在 joe 之后:th:if="${session.user.username == 'joe'}"
    【解决方案2】:

    我试过了,它对我有用:

    th:text="${session.user['tel']}"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-31
      • 2014-03-10
      • 2014-03-07
      • 2023-03-18
      • 1970-01-01
      • 2011-10-17
      相关资源
      最近更新 更多