Thymeleaf嵌套循环遍历Comment集合报错:SpringEL表达式异常
问题解决:Thymeleaf嵌套遍历Feed与Comment的异常处理
核心问题原因
你遇到的Exception evaluating SpringEL expression: "cd.get(0).c_text"异常,本质是两个问题:
- 当前Feed的
comment列表要么为null,要么是空集合,直接调用get(0)会触发索引越界或空指针类的EL表达式错误; - 直接取第一个元素的写法,本身就不符合“嵌套循环遍历所有评论”的需求。
解决方案步骤
1. 先确保实体类中评论列表不会为null
在Feed实体类里初始化comment列表,避免后续模板处理时遇到null:
public class Feed { // 其他属性... private List<Comment> comment = new ArrayList<>(); // 初始化空列表 // getter、setter、构造方法... }
也可以在构造方法中完成初始化,确保任何情况下feed.getComment()返回的都是一个列表(空或有元素)。
2. 正确的Thymeleaf嵌套循环写法
遍历listfeedDocuments的同时,对每个Feed的评论列表做循环遍历,同时增加空列表判断:
<!-- 遍历所有Feed --> <div th:each="feed : ${listfeedDocuments}"> <!-- 显示Feed自身属性,示例: --> <h3 th:text="${feed.feedTitle}">Feed标题</h3> <p th:text="${feed.feedContent}">Feed内容</p> <!-- 嵌套遍历该Feed下的所有评论 --> <div class="comments-section"> <!-- 先判断评论列表是否为空 --> <div th:if="${#lists.isEmpty(feed.comment)}"> <p>暂无评论</p> </div> <!-- 遍历评论 --> <div th:if="${not #lists.isEmpty(feed.comment)}" th:each="comment : ${feed.comment}"> <div class="comment-item"> <span th:text="'评论ID:' + ${comment.c_id}"></span> <p th:text="${comment.c_text}"></p> </div> </div> </div> </div>
关键说明
- 使用Thymeleaf的
#lists.isEmpty()工具方法判断列表状态,避免空指针或索引越界; - 嵌套循环必须基于当前Feed的
comment列表,通过th:each="comment : ${feed.comment}"遍历每一条评论,而不是直接取固定索引的元素; - 实体类初始化列表是基础,否则即使模板加了判断,也可能因为null导致异常。
内容的提问来源于stack exchange,提问作者Ali
相关产品推荐
相关产品推荐

