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

SpringBoot集成Thymeleaf判断列表为空报错求助

问题解决:Thymeleaf判断列表为空报错

核心错误原因

从报错信息可直接定位问题:你的SpringEL表达式缺少右括号

Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "#lists.isEmpty(listPersons" (template: "index" - line 15, col 8)

表达式#lists.isEmpty(listPersons)未闭合,这是触发报错的直接原因。

正确写法示例

1. 推荐:使用Thymeleaf列表工具类(安全处理null)

Thymeleaf的#lists工具类可安全处理列表为null的场景,不会触发空指针异常,正确写法:

<h2 th:if="${#lists.isEmpty(listPersons)}">No hay personas</h2>
<div th:if="${!#lists.isEmpty(listPersons)}">
    <!-- 列表非空时的渲染内容 -->
</div>

注意:否定判断的语法是!#lists.isEmpty(...),而非你之前尝试的#!lists.isEmpty(...),后者属于语法错误。

2. 直接调用列表方法(需确保列表非null)

如果能保证personaService.getAll()永远返回空列表而非null,也可以用原生列表方法:

<h2 th:if="${listPersons.isEmpty()}">No hay personas</h2>
<div th:if="${!listPersons.isEmpty()}">
    <!-- 列表非空时的渲染内容 -->
</div>

但如果personaService.getAll()可能返回null,这种写法会触发空指针异常,优先推荐第一种写法。

额外检查项

  • 确认personaService.getAll()的返回逻辑:若存在返回null的情况,必须使用#lists.isEmpty()处理
  • 验证model.addAttribute("listPersons", personaService.getAll())确实在请求模板的Controller方法中执行,未被条件分支跳过

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 03:06:39