Thymeleaf拆分数据多行展示报错:EL1007E属性未找到
问题修复:Thymeleaf表格渲染报错EL1007E
问题背景
从SpringBoot后端获取summaryList数据(列表元素为SummaryDTO对象,包含aliquotID、ic50、fold、refID、ic50_ref属性),需要在Thymeleaf中生成表格,每条数据拆分为两行展示:
- 第一行:
aliquotID(Name列)、ic50(IC50列)、fold(Fold列) - 第二行:
refID(Name列)、ic50_ref(IC50列)、空(Fold列)
运行时报错:
org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'aliquotID' cannot be found on null
原代码
<table border="1" cellpadding="10"> <thead> <tr> <th>Name</th> <th>IC50</th> <th>Fold</th> </tr> </thead> <tbody> <tr th:if="${#lists.isEmpty(summaryList)}"> <td colspan="9">no data</td> </tr> <p>List Size: [[${summaryList.size()}]]</p> <tr th:each="dto: ${summaryList}"> <tr> <td th:text="${dto.aliquotID}"></td> <td th:text="${dto.ic50}"></td> <td th:text="${dto.fold}"></td> </tr> <tr> <td th:text="${dto.refID}"></td> <td th:text="${dto.ic50_ref}"></td> </tr> </tr> </tbody> </table>
错误原因
- HTML结构非法:
tbody的直接子元素只能是<tr>,不能包含<p>标签;同时<tr>标签不能嵌套,这会导致Thymeleaf解析时上下文混乱,dto变量可能被解析为null。 - 空值未处理:
summaryList中可能存在null元素,直接访问null对象的属性会触发EL异常。 - 列数不匹配:空数据提示的
colspan写为9,实际表格只有3列,属于无效配置。
修复后的代码
<table border="1" cellpadding="10"> <thead> <tr> <th>Name</th> <th>IC50</th> <th>Fold</th> </tr> </thead> <tbody> <!-- 空数据提示,修正colspan为实际列数3 --> <tr th:if="${#lists.isEmpty(summaryList)}"> <td colspan="3">no data</td> </tr> <!-- 列表长度展示,放在合法的tr结构内 --> <tr th:unless="${#lists.isEmpty(summaryList)}" style="border: none;"> <td colspan="3"> <p>List Size: [[${summaryList.size()}]]</p> </td> </tr> <!-- 使用th:block遍历,避免tr嵌套的非法结构,同时过滤null元素 --> <th:block th:each="dto : ${summaryList}" th:if="${dto != null}"> <tr> <td th:text="${dto.aliquotID}"></td> <td th:text="${dto.ic50}"></td> <td th:text="${dto.fold}"></td> </tr> <tr> <td th:text="${dto.refID}"></td> <td th:text="${dto.ic50_ref}"></td> <td></td> <!-- 第二行Fold列留空,保证列数对齐 --> </tr> </th:block> </tbody> </table>
关键修复点
- 用
<th:block>替代外层<tr>作为遍历容器,彻底避免<tr>嵌套的非法HTML结构。 - 将列表长度展示的
<p>标签移到合法的<tr>内,保证tbody结构符合规范。 - 增加
th:if="${dto != null}"过滤列表中的null元素,防止访问null对象属性触发异常。 - 修正空数据提示的
colspan为3,匹配表格实际列数。
内容的提问来源于stack exchange,提问作者prashanth
相关产品推荐
相关产品推荐

