Thymeleaf:使用#session 的偶然错误 - 异常评估 SpringEL 表达式

Thymeleaf: Occasional error using #session - Exception evaluating SpringEL expression

我们正在使用 Spring webflow + ThymeLeaf 并尝试访问 html 页面中的 session.getAttribute()。

Thymeleaf 有点新,我知道 Thymeleaf 有 2 种方法来处理会话,即。 ${session.something} 和 ${#session.getAttribute('something')}。

我们使用的代码类似于下面的代码,偶尔会失败。

<div th:if="${(#session.getAttribute('booleanAttribute'))}">  
...
</div>

在本地环境中,我从未见过故障,而且它按预期工作。在生产中,这失败了。 30 分钟内出现 200 次错误 -

org.thymeleaf.exceptions.TemplateProcessingException:  Exception evaluating SpringEL expression: "(#session.getAttribute('booleanAttribute'))" (template: "base" - line 80, col 10)

我不太愿意在不理解为什么在本地工作正常的情况下进行空检查以查看 (#session) 是否为空。所以我有这个问题 -

以上可能有什么问题?我如何在本地重现以确认我放置的修复程序适用于所有环境?

根据 docs:

#session : direct access to the javax.servlet.http.HttpSession object associated with the current request.

在我的测试中,#session 在会话过期时为空。在用户会话过期的情况下,使用 #session 会抛出空点异常 (Method call: Attempted to call method getAttribute(java.lang.String) on null context object)。您应该可以通过删除 JSESSIONID cookie 来测试这一点。

另一方面,

${session} 是一个 SessionAttributesMap,它似乎永远不会为空——即使没有有效的会话。在那种情况下,表达式 ${session.booleanAttribute} 仍然有效,只是求值为 false。