You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Thymeleaf如何处理不存在的会话属性?语法错误求助

问题解决:Thymeleaf会话属性默认值语法错误修正

你的错误在于将Spring EL的?:默认值运算符写在了${}表达式外部,导致Thymeleaf无法正确解析语法。

错误写法分析

你原本的代码:

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

这里?:是Spring EL的核心运算符,必须包含在${}内部,否则Thymeleaf会将其视为无效语法片段。

正确写法

推荐使用Thymeleaf内置的session对象直接访问会话属性(更简洁直观):

<input type="hidden" id="foo" name="foo" th:value="${session.foo ?: 'tai-bo'}" />

如果坚持使用#session.getAttribute()方法,需将整个逻辑表达式放在${}中:

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

原理说明

  • 当会话中不存在foo属性时,session.foo或#session.getAttribute('foo')会返回null
  • Spring EL的?:运算符会自动判断左侧值是否为null/空值,若是则使用右侧的默认值'tai-bo',彻底避免因属性缺失引发的表达式解析异常

内容的提问来源于stack exchange,提问作者Micho Rizo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 23:06:33