1、评论功能
①、创建Comment实体类,其中包括ID,nickname等元素
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String nickname; private String email; private String content; private String avatar; @Temporal(TemporalType.TIMESTAMP) private Date createTime; @ManyToOne private News news; @OneToMany(mappedBy = "parentComment") private List<Comment> replyComments=new ArrayList<>(); @ManyToOne private Comment parentComment; private boolean adminComment;
②、在News实体中添加List<Comment>元素,并将其注解为@OneToMany(mappedBy = "news")
③、创建CommentService接口与CommentRepository接口
public interface CommentService { List<Comment> listCommentByNewId(Long newId); Comment saveComment(Comment comment); }
public interface CommentRepository extends JpaRepository<Comment,Long> { List<Comment> findByNewsIdAndParentCommentNull(Long newId, Sort sort); }
④、继承这个接口并进行实现;CommentServiceImpl中还应该实现展示,合并评论等功能函数
public Comment saveComment(Comment comment) { Long parentCommentId=comment.getParentComment().getId(); if(parentCommentId!=-1){ comment.setParentComment(commentRepository.findById(parentCommentId).orElse(null)); }else{ comment.setParentComment(null); } comment.setCreateTime(new Date()); return commentRepository.save(comment); }
private void combineChildren(List<Comment> comments){ for(Comment comment:comments){ List<Comment> replys1=comment.getReplyComments(); for(Comment reply1:replys1){ //循环迭代,找出子代,存放在tempReplys里 recursively(reply1); } comment.setReplyComments(tempReplys); //清除temp tempReplys=new ArrayList<>(); } }
⑤、创建CommentController类,用于实现前后端数据交互;以保存操作为例
@PostMapping("/comments") private String post(Comment comment, HttpSession session){ Long newId=comment.getNews().getId(); comment.setNews(newService.getNew(newId)); User user=(User) session.getAttribute("user"); if(user!=null){//是管理员,因为只有管理员能登录 comment.setAdminComment(true); comment.setAvatar(avatar); }else{ comment.setAvatar(avatar); } commentService.saveComment(comment); return "redirect:/comments/"+newId; }
2、分类与标签页面
以TagShowController控制类为例,Type的相应控制类类似
@Controller public class TagShowController { @Autowired private NewService newService; @Autowired private TagService tagService; @GetMapping("/tags/{id}") public String tags(@PageableDefault(size=8,sort = {"updateTime"},direction = Sort.Direction.DESC) Pageable pageable, @PathVariable Long id, Model model){ List<Tag> tags=tagService.listTagTop(20); if(id==-1){ id=tags.get(0).getId(); } NewQuery newQuery=new NewQuery(); newQuery.setTypeId(id); model.addAttribute("tags",tags); model.addAttribute("page",newService.listNew(id,pageable)); model.addAttribute("activeTagId",id); return "tags"; } }