一:
首先通过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>