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

Thymeleaf子元素无法访问变量:嵌套th:each调用getAdminList()报错

Thymeleaf嵌套th:each调用category方法报空指针异常

问题场景

在Thymeleaf模板中,父级<li>通过th:each="category : ${categories}"循环遍历列表,父元素内调用category.getId()、category.getImg()等方法均正常,但在嵌套的子<li>的th:each中调用${category.getAdminList()}时抛出异常,报错信息如下:

Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1011E: Method call: Attempted to call method getAdminList() on null context object

原代码示例:

<li
  class="setting"
  th:each="category : ${categories}"
  th:id="|category${category.getId()}|"    <!-- works -->
>
  <div class="setting_top">
    <div class="setting_img_frame">
      <img th:src="@{/images/{img}(img = ${category.getImg()})}" alt="" />    <!-- works -->
    </div>
    <div class="setting_right">
      <div class="setting_right_top"></div>
      <div class="setting_right_bottom" th:text="${category.getAbout()}"></div>    <!-- also works.. -->
    </div>
  </div>

  <div class="setting_bottom">
    <li
      class="setting_tag"
      th:each="admin : ${category.getAdminList()}"    <!-- Error here, category does not exist -->
      th:text="${admin}"
      th:title="${admin}"
    ></li>
  </div>

</li>

问题原因

核心问题是HTML结构不规范:<li>元素的直接父级必须是<ul>或<ol>这类列表容器,不能直接在<li>内部嵌套<li>。浏览器会自动修正不规范的HTML结构,这会干扰Thymeleaf的变量上下文传递,导致嵌套的th:each中无法正确获取category变量,最终出现“调用null对象方法”的异常。

解决方案

  1. 修正HTML结构:在嵌套的<li class="setting_tag">外层添加<ul>或<ol>容器,确保列表元素的层级符合规范:
<li
  class="setting"
  th:each="category : ${categories}"
  th:id="|category${category.getId()}|"
>
  <div class="setting_top">
    <div class="setting_img_frame">
      <img th:src="@{/images/{img}(img = ${category.getImg()})}" alt="" />
    </div>
    <div class="setting_right">
      <div class="setting_right_top"></div>
      <div class="setting_right_bottom" th:text="${category.getAbout()}"></div>
    </div>
  </div>

  <div class="setting_bottom">
    <!-- 添加ul包裹内部li,修正层级结构 -->
    <ul>
      <li
        class="setting_tag"
        th:each="admin : ${category.getAdminList()}"
        th:text="${admin}"
        th:title="${admin}"
      ></li>
    </ul>
  </div>

</li>
  1. 额外防护(可选):如果后端返回的category.getAdminList()可能为null,可以使用Thymeleaf的安全导航操作符?.,避免潜在的空指针:
<!-- 使用安全导航操作符,adminList为null时返回空,不会触发循环 -->
<li
  class="setting_tag"
  th:each="admin : ${category?.getAdminList()}"
  th:text="${admin}"
  th:title="${admin}"
></li>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 15:40:28