Thymeleaf如何处理不存在的会话属性

huangapple go评论51阅读模式
英文:

Thymeleaf how to handle non-existent session attribute

问题

我不经常使用Thymeleaf...

我有一个Thymeleaf的HTML模板,其中包含一个隐藏的输入字段:

<input type="hidden" id="foo" name="foo" th:value="${#session.getAttribute('foo')}" />

如果我确实在会话中有一个名为foo的属性,它可以正常工作。但有时根据用户选择的选项,我的会话中可能没有foo属性,然后会出现以下错误:

处理模板“somePage”时出现异常:评估SpringEL表达式时发生异常:“#session.getAttribute('foo')”(模板:“somePage” - 第29行,第6列)

我知道我应该有类似于"if存在则"的东西,但我无法正确使用语法:

th:value="${#session.getAttribute('foo') ?: 'tai-bo'}" />

有人可以指出我的错误吗?先感谢了。

英文:

I dont have to mess with Thymeleaf too often ...

I have an thymeleaf html template with a hidden input:

&lt;input type=&quot;hidden&quot; id=&quot;foo&quot; name=&quot;foo&quot; th:value=&quot;${#session.getAttribute(&#39;foo&#39;)}&quot; /&gt;

Works fine if I really do have a session attribute named foo. But sometimes depending on user selected option I don't have a foo attribute in my session. Get the following error:

Exception processing template &quot;somePage&quot;: Exception evaluating SpringEL expression: &quot;#session.getAttribute(&#39;foo&#39;)&quot; (template: &quot;somePage&quot; - line 29, col 6)&gt;

I know I should have something like if exist else but I cannot get the syntax right:

th:value=&quot;${#session.getAttribute(&#39;foo&#39;)} ?: &#39;tai-bo&#39;&quot; /&gt;

Can someone point out my error? Thanks in advance.

答案1

得分: 1

试试这个(我用这个方法)

<input type="hidden" id="foo" th:value="${#session.getAttribute('foo') != null ? 'foo不为空' : 'foo为空'}" />

注意,从Thymeleaf 3.1开始,表达式中不再支持session对象。

英文:

Try this (works for me)

&lt;input type=&quot;hidden&quot; id=&quot;foo&quot; th:value=&quot;${#session.getAttribute(&#39;foo&#39;) != null ? &#39;foo is not null&#39; : &#39;foo is null&#39;}&quot; /&gt; 

Note also that support for the session object in expressions is removed starting with Thymeleaf 3.1.

huangapple
  • 本文由 发表于 2023年2月24日 03:52:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75549686.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定