英文:
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:
<input type="hidden" id="foo" name="foo" th:value="${#session.getAttribute('foo')}" />
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 "somePage": Exception evaluating SpringEL expression: "#session.getAttribute('foo')" (template: "somePage" - line 29, col 6)>
I know I should have something like if exist else but I cannot get the syntax right:
th:value="${#session.getAttribute('foo')} ?: 'tai-bo'" />
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)
<input type="hidden" id="foo" th:value="${#session.getAttribute('foo') != null ? 'foo is not null' : 'foo is null'}" />
Note also that support for the session object in expressions is removed starting with Thymeleaf 3.1.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论