Java开发学习.Day11

基于Springboot实现 评论、分类和标签功能

本文内容是基于Java开发学习.Day10内容上所实现的


评论功能

在每条新闻下,游客或博主均可对用户进行评论

代码实现

新建一个comment类,用于存储评论者姓名、评论内容、评论时间等信息,具体内容如下:

@Entity
@Table(name="t_comment")
public class Comment {

    @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> replyComment = new ArrayList<>();

    @ManyToOne
    private Comment parentComment;

    //管理员评论
    private boolean adminComment;

    public Comment() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getAvatar() {
        return avatar;
    }

    public void setAvatar(String avatar) {
        this.avatar = avatar;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public News getNews() {
        return news;
    }

    public void setNews(News news) {
        this.news = news;
    }

    public List<Comment> getReplyComment() {
        return replyComment;
    }

    public void setReplyComment(List<Comment> replyComment) {
        this.replyComment = replyComment;
    }

    public Comment getParentComment() {
        return parentComment;
    }

    public void setParentComment(Comment parentComment) {
        this.parentComment = parentComment;
    }

    public boolean isAdminComment() {
        return adminComment;
    }

    public void setAdminComment(boolean adminComment) {
        this.adminComment = adminComment;
    }

    @Override
    public String toString() {
        return "Comment{" +
                "id=" + id +
                ", nickname='" + nickname + '\'' +
                ", email='" + email + '\'' +
                ", content='" + content + '\'' +
                ", avatar='" + avatar + '\'' +
                ", createTime=" + createTime +
                ", news=" + news +
                ", replyComment=" + replyComment +
                ", parentComment=" + parentComment +
                ", adminComment=" + adminComment +
                '}';
    }
}

由于该功能涉及到回复他人评论的功能,即父评论和子评论的关系。需要在dao层中创建CommentRepository进行查询

public interface CommentRepository extends JpaRepository<Comment,Long> {
    
    List<Comment> findByNewsIdAndParentCommentNull(Long newId, Sort sort);

}

创建CommentService

public interface CommentService {

    //展示所有评论
    List<Comment> listCommentByNewId(Long newId);

    //发表评论
    Comment saveComment(Comment comment);

}

实现上述接口,主要包括查看评论和保存评论两种功能

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    CommentRepository commentRepository;



    @Override
    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);
    }

    @Override
    public List<Comment> listCommentByNewId(Long newId) {
        Sort sort = Sort.by("createTime");
        List<Comment> comments = commentRepository.findByNewsIdAndParentCommentNull(newId,sort);
        System.out.println("运行到listCommentByNewId");
        return eachComment(comments);
    }

    //循环查找所有评论
    private List<Comment> eachComment(List<Comment> comments){
        List<Comment> commentsView = new ArrayList<>();
        System.out.println("eachComment");
        for(Comment comment:comments){
            Comment c = new Comment();
            BeanUtils.copyProperties(comment,c);
            commentsView.add(c);
        }
        //合并评论的各层子代到第一代集合
        combineChildrenComment(commentsView);
        return commentsView;
    }

    private void combineChildrenComment(List<Comment> comments){
        System.out.println("combineChildrenComment");
        for(Comment comment:comments){
            List<Comment> replies = comment.getReplyComment();
            for(Comment reply : replies){
                //循环迭代,找出子代  存放在临时存放区
                recursively(reply);
            }
            comment.setReplyComment(tempReplies);
            //清除临时存放区
            tempReplies = new ArrayList<>();
        }
    }

    //临时找出子代
    private List<Comment> tempReplies = new ArrayList<>();

    private void recursively(Comment comment){
        tempReplies.add(comment);  //顶节点添加到临时存放区
        if(comment.getReplyComment().size()>0){
            List<Comment> replies = comment.getReplyComment();
            for(Comment reply:replies){
                tempReplies.add(reply);
                if(comment.getReplyComment().size()>0){
                    recursively(reply);
                }
            }
        }
    }

}

添加controller

@Controller
public class CommentController {

    @Autowired
    CommentService commentService;
    @Autowired
    NewService newService;
    //保存

    private String avatar = "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1091405991,859863778&fm=26&gp=0.jpg";

    @GetMapping("/comments/{newId}")
    public String comments(@PathVariable Long newId, Model model){
        System.out.println("运行到这里"+newId);
        model.addAttribute("comments",commentService.listCommentByNewId(newId));
        return "new::commentList";
    }

    @PostMapping("/comments")
    public 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);

        commentService.saveComment(comment);
        return "redirect:/comments/"+newId;
    }
}

效果展示

在这里插入图片描述

分类功能

该功能是通过文章类型对文章进行分类

代码实现

首先,在dao中添加type类新的查询方式

public interface TypeRepository extends JpaRepository<Type,Long> {
    Type findByName(String name);

    @Query("select t from Type t")
    List<Type> findTop(Pageable pageable);
}

在service中声明新的方法

public interface TypeService {
    //不分页的List  在查找新闻界面显示出
    List<Type> listTypeTop(Integer size);

}

实现上述方法

@Service
public class TypeServiceImpl implements TypeService {

    @Autowired
    private TypeRepository typeRepository;

    @Override
    public List<Type> listTypeTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC,"news.size");
        Pageable pageable = PageRequest.of(0,size,sort);
        return typeRepository.findTop(pageable);
    }
}

在controller中添加路由

@Controller
public class TypeShowController {

    @Autowired
    private TypeService typeService;
    @Autowired
    private NewService newService;

    @GetMapping("/types/{id}")
    public String types(@PageableDefault(size = 8,sort = {"updateTime"},direction = Sort.Direction.DESC)Pageable pageable,
                        @PathVariable Long id, Model model){
        List<Type> types = typeService.listTypeTop(20);
        if(id==-1){
            id = types.get(0).getId();
        }
        NewQuery newQuery = new NewQuery();
        newQuery.setTypeId(id);
        model.addAttribute("types",types);
        model.addAttribute("page",newService.listNew(pageable,newQuery));
        model.addAttribute("activeTypeId",id);
        return "types";
    }
}

效果展示

在这里插入图片描述

标签功能

该功能是通过文章标签对文章进行分类

代码实现

首先,在dao中添加tag类新的查询方式

public interface TagRepository extends JpaRepository<Tag,Long> {
    Tag findByName(String name);

    @Query("select t from Tag t")
    List<Tag> findTop(Pageable pageable);
}


在service中声明新的方法

public interface TagService {
    List<Tag> listTagTop(Integer size);
}


实现上述方法

@Service
public class TagServiceImpl implements TagService {

    @Autowired
    private TagRepository tagRepository;

    @Override
    public List<Tag> listTagTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC,"newsList.size");
        Pageable pageable = PageRequest.of(0,size,sort);
        return tagRepository.findTop(pageable);
    }
}

在controller中添加路由

@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();
        }
        model.addAttribute("tags",tags);
        model.addAttribute("page",newService.listNew(pageable));
        model.addAttribute("activeTagId",id);
        return "tags";
    }

}


效果展示

在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值