一:
首先通過vo把不同的對象封裝起來。
代碼示例:
我的vo對象:
public class ViewObject {
private Map<String, Object> objs = new HashMap<>();
public void set(String key, Object value) {
objs.put(key, value);
}
public Object get(String key) {
return objs.get(key);
}
}
Controller:
List<Blog> blogList = blogService.findAllBlog();
List<ViewObject> vos = new ArrayList<>();
for (Blog blog : blogList) {
ViewObject vo = new ViewObject();
User user = userService.getUserById(blog.getUserid());// 返回一個user對象
logger.error(user.getName());
vo.set("blog", blog);
vo.set("user", user);
vos.add(vo);
}
model.addAttribute("vos", vos);
html代碼部分:
<div class="col-md-8" th:if="${not #lists.isEmpty(vos)}" > <!-- 空值判斷 -->
<div th:each="blogs,userStat:${vos}">
<li th:text="${blogs.get('blog').title}"></li>
<li th:text="${blogs.get('user').name}"></li>
</div>
這樣就可以把list裏面的map對象一個個都迭代出來了。。。。注意下userStat是個狀態變量。
寫得應該很清楚了。
參考:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
二:vo中存放的是list集合的遍歷方法
例子:
controller:
List<Comment> comments = commentService.getAllCommentByblogId(blogId);
ViewObject vos = new ViewObject();
vos.set("user", user);
vos.set("blog", blog);
vos.set("comment", commentsAndUser);
html部分:
<div class="card-block" id="mainContainer"
th:if="${not #lists.isEmpty(vos)}">
<div class="row" th:each="com,userStat:${vos.get('comment')}" >
<span th:text="${com.id}"></span>
</div>
</div>