【学习日记】(SpringBoot-part 6)新闻管理系统—评论功能/分类和标签功能

新闻评论功能

效果展示

可以直接在新闻底下输入姓名和邮箱评论,也可以回复别人发表的评论

在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述

功能实现

  1. 新建实体类
    在pojo目录下新建一个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 +
                '}';
    }
}
  1. 新建repository
    在dao目录下新建一个CommentRepository,继承jpa,并且声明一个用来查找父级评论的方法
public interface CommentRepository extends JpaRepository<Comment,Long> {

    //根据新闻id和父级评论是空查询
//    @Query
    List<Comment> findByNewsIdAndParentCommentNull(Long newId, Sort sort);

}
  1. 新建Service
    在Service目录下新建一个CommentService的接口方法,声明发表评论方法和查找所有评论方法,保存评论的方法实现只需要查找到是否有父级评论,并调用jpa保存到数据库中即可,但按父子级进行评论的展示需要循环迭代找出所有子代评论,并申请一个临时存放区域,再按照父->子的方向保存到一个commentsView链表中
public interface CommentService {
    
    //发表评论
    Comment saveComment(Comment comment);
    //展示所有评论
    List<Comment> listCommentByNewId(Long newId);
}

之后再在CommentServiceImpl中实现该方法,这里

@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);
                }
            }
        }
    }
}
  1. 新建controller

在web目录下新建一个Controller,由于该部分功能针对所有用户,所以需要再全局web下进行创建,目前再界面中输入的只能是昵称和邮箱和评论,头像直接在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;
    }
}

在该文件中,comments方法用来展示当前新闻的评论,这里的listCommentByNewId(newID)方法将直接从service中实现的方法返回的链表里按父子级进行评论展示,而post方法用于提交输入的评论,用到service中的save方法

分类功能

效果展示

根据当前的分类目录进行相应的新闻展示
在这里插入图片描述在这里插入图片描述

功能实现

  1. 添加TypeRepository方法
    由于在实体类中已经声明了各个属性,所以直接从TypeRepository添加查询方法开始,在TypeRepository接口中添加方法
    @Query("select t from Type t")
    List<Type> findTop(Pageable pageable);
  1. 添加TypeService方法
    和TypeRepository类似,直接在TypeService中添加方法
    List<Type> listTypeTop(Integer size);

并在Impl中实现,实现的时候指定是通过分类下的新闻总数进行排序,进而将新闻多的分类显示在前面

    //显示在主页
    @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);
    }
  1. 新建TypeShowController

在web目录下新建一个TypeShowController,并按照更新时间再对当前分类下的新闻进行排序展示

@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";
    }
}

需要调用到的NewService中的查找方法之前已经实现过了

标签功能

效果展示

在这里插入图片描述

功能实现

功能实现步骤和type差不多,只是在调用NewService处的方法传参不一样,需要对每种传参都进行方法实现

  1. 添加TagRepository方法
    @Query("select t from Tag t")
    List<Tag> findTop(Pageable pageable);
  1. 添加TagService方法
    //显示在主页
    List<Tag> listTagTop(Integer size);

在Impl中实现

    @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);
    }
  1. 新建TagShowController
    在web目录下新建一个TagShowController
@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";
    }
}

这里需要在NewService中新声明一个只有pageable参数的listNew方法,并在Impl中实现

    //主页分页展示
    Page<News> listNew(Pageable pageable);

Impl实现

@Override
    public Page<News> listNew(Pageable pageable) {
        return newRepository.findAll(pageable);
    }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值