回复:
setparentcommment
//回复时 +setparentcomment + 局部刷新 回显
@PostMapping("/comments")
public String post(Comment comment, HttpSession session) {
Long blogId = comment.getBlog().getId();
comment.setBlog(blogService.getBlog(blogId));
User user = (User) session.getAttribute("user");
if (user != null) {
comment.setAvatar(user.getAvatar());
comment.setAdminComment(true);
} else {
// comment.setAvatar(avatar);
}
User user1=(User)session.getAttribute("user");
// comment.setUser_id(user.getId());
comment.setUser(user1);
comment.setUid(user1.getId());
commentService.saveComment(comment,session);
return "redirect:/comments/" + blogId;
}
到返回数据的function:
@GetMapping("/comments/{blogId}")
public String comments(@PathVariable Long blogId, Model model) {
model.addAttribute("comments", commentService.listCommentByBlogId(blogId));
return "blog :: commentList";
}
service层实现类
function:listCommentByBlogId:
分为几个部分
part1: findByBlogIdAndParentCommentNull()
@Override
public List<Comment> listCommentByBlogId(Long blogId) {
Sort sort = new Sort("createTime");
//获取父节点集合comments
List<Comment> comments = commentRepository.findByBlogIdAndParentCommentNull(blogId,sort);
return eachComment(comments);
}
part2 : eachComment()
简单的复制到commentsView ,也是父节点集合
private List<Comment> eachComment(List<Comment> comments) {
List<Comment> commentsView = new ArrayList<>();
for (Comment comment : comments) {
Comment c = new Comment();
BeanUtils.copyProperties(comment,c);
commentsView.add(c);
}
//合并评论的各层子代到第一级子代集合中
combineChildren(commentsView);
return commentsView;
}
part3: combineChildren()
set父节点评论的子评论集
private void combineChildren(List<Comment> comments) {
for (Comment comment : comments) {
List<Comment> replys1 = comment.getReplyComments();
for(Comment reply1 : replys1) {
//循环迭代,找出子代,存放在tempReplys中
recursively(reply1);
}
//修改顶级节点的reply集合为迭代处理后的集合
comment.setReplyComments(tempReplys);
//清除临时存放区
tempReplys = new ArrayList<>();
}
}
part4: recursively()
通过递归获取当前父节点的子评论集合。
private void recursively(Comment comment) {
tempReplys.add(comment);//顶节点添加到临时存放集合
if (comment.getReplyComments().size()>0) {
List<Comment> replys = comment.getReplyComments();
for (Comment reply : replys) {
tempReplys.add(reply);
if (reply.getReplyComments().size()>0) {
recursively(reply);
}
}
}
}