6_1_评论中心

一 需求描述

1. 当分享发布一条头条消息后,当前用户可在指定消息内评论头条;

2. 评论完成后能够在当前页面显示以及评论数的改变

效果描述:

二 具体实现

1. DB

DROP TABLE IF EXISTS `comment`;
CREATE TABLE `comment`(
  `id` int NOT NULL AUTO_INCREMENT,
  `content`  TEXT NOT NULL comment ‘评论内容‘,
  `entity_id` INT NOT NULL comment ‘实体id‘,
  `entity_type` INT NOT NULL comment ‘实体类型‘,
  `created_date` DATETIME NOT NULL comment ‘创建日期‘,
  `user_id` INT NOT NULL comment ‘评论用户id‘,
  `status` INT NOT NULL DEFAULT 0 comment ‘评论会话状态‘,
  PRIMARY KEY(`id`),
  INDEX `entity_index `(`entity_id` ASC ,`entity_type` ASC )

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT=‘评论中心‘;

2. Model

package com.nowcoder.model;

import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Created by Administrator on 2017/4/29.
 */
@Component
public class Comment {

    private int id;
    private String content;
    private int entityId;
    private int entityType;
    private Date createdDate;
    private int userId;
    private int status;

    public int getId() {
        return id;
    }

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

    public String getContent() {
        return content;
    }

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

    public int getEntityId() {
        return entityId;
    }

    public void setEntityId(int entityId) {
        this.entityId = entityId;
    }

    public int getEntityType() {
        return entityType;
    }

    public void setEntityType(int entityType) {
        this.entityType = entityType;
    }

    public Date getCreatedDate() {
        return createdDate;
    }

    public void setCreatedDate(Date createdDate) {
        this.createdDate = createdDate;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }
}

3. Dao:

int addCommnet(Comment comment); 添加评论
 List<Comment> selectByEntity(@Param("entityId") int entityId, @Param("entityType") int entityType);  :  根据entityId查询所有评论;
 int getCommentCount(@Param("entityId") int entityId, @Param("entityType") int entityType);   :  获取所有评论数量
void updateStatus(@Param("entityId") int entityId,
                      @Param("entityType") int entityType,
                      @Param("status") int status);  删除评论

有两个点要说一下: entityId 和entityType 一起 代表一个咨询。这里type即为news,而entityId 即为newsId.假如还有news,topics等等别的可以直接套用。

第二个就是删除评论,并不是直接删除,而是将status设置为1.

package com.nowcoder.dao;

import com.nowcoder.model.Comment;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * Created by Administrator on 2017/4/29.
 */
@Mapper
public interface CommentDao {
    String TABLE_NAME = "comment";
    String INSERT_FIELDS = "content, entity_id, entity_type, created_date, user_id, status";
    String SELECT_FIELDS = "id," + INSERT_FIELDS;

    @Insert({"insert into", TABLE_NAME, "(", INSERT_FIELDS,
            ") values(#{content},  #{entityId}, #{entityType}, #{createdDate}, #{userId}, #{status})" })
    int addCommnet(Comment comment);

    @Select({"select", SELECT_FIELDS, "from", TABLE_NAME,
            "where entity_id = #{entityId} and entity_type=#{entityType} order by id desc"})
    List<Comment> selectByEntity(@Param("entityId") int entityId, @Param("entityType") int entityType);

    @Select({"select count(id) from", TABLE_NAME,
            "where entity_id = #{entityId} and entity_type=#{entityType}"})
    int getCommentCount(@Param("entityId") int entityId, @Param("entityType") int entityType);

    @Update({"update", TABLE_NAME, "set status=#{status} where entity_id = #{entityId} and entity_type=#{entityType}"})
    void updateStatus(@Param("entityId") int entityId,
                      @Param("entityType") int entityType,
                      @Param("status") int status);

}

4. Service:

package com.nowcoder.service;

import com.nowcoder.dao.CommentDao;
import com.nowcoder.model.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Administrator on 2017/4/29.
 */
@Service
public class CommentService {

    @Autowired
    CommentDao commentDao;

    public List<Comment> getCommentsByEntity(int entityId, int entityType){
        return commentDao.selectByEntity(entityId, entityType);
    }

    public int addComment(Comment comment){
        return commentDao.addCommnet(comment);
    }

    public int getCommentCount(int entityId, int entityType){
        return commentDao.getCommentCount(entityId, entityType);
    }

    public void deleteComment(int entityId, int entityType){
        //模拟删除评论,status=1表示会话失效即被删除不显示
        commentDao.updateStatus(entityId, entityType, 1);
    }

}

5.Controller:

(1)增加评论:

    /**
     * 增加评论
     * @param newsId
     * @param content
     * @return
     */
    @RequestMapping(path = {"/addComment"}, method = {RequestMethod.POST})
    public String addComment(@RequestParam("newsId") int newsId,
                             @RequestParam("content") String content){

        try{
            //防止评论中有转义字符
            content = HtmlUtils.htmlEscape(content);
            //过滤评论内容content

            Comment comment = new Comment();
            comment.setUserId(hostHolder.getUser().getId());
            comment.setEntityId(newsId);
            comment.setEntityType(EntityType.ENTITY_NEWS);
            comment.setContent(content);
            comment.setCreatedDate(new Date());
            comment.setStatus(0);//0 有效,1 表示评论被删除

            commentService.addComment(comment);

            //更新评论数量
            int count = commentService.getCommentCount(comment.getEntityId(), comment.getEntityType());
            newsService.updateCommentCount(comment.getEntityId(), count);
            //异步化更新数量
        }catch (Exception e){
            logger.error("增加评论失败!" + e.getMessage());
        }
        return "redirect:/news/" + String.valueOf(newsId);
    }

(2)显示评论:

    /**
     * 查看资讯详情页
     * @param newsId
     * @param model
     * @return
     */
    @RequestMapping(path = {"/news/{newsId}"}, method = {RequestMethod.GET})
    public String newsDetail(@PathVariable("newsId") int newsId, Model model){
        News news = newsService.getById(newsId);
        //显示评论内容
        if(news != null){
            List<Comment> commentList = commentService.getCommentsByEntity(news.getId(), EntityType.ENTITY_NEWS);
            List<ViewObject> commentVOs = new ArrayList<>();
            for(Comment comment : commentList){
                ViewObject vo = new ViewObject();
                vo.set("comment", comment);
                vo.set("user", userService.getUser(comment.getUserId()));
                commentVOs.add(vo);
            }
            model.addAttribute("comments", commentVOs);
        }

        //评论
        model.addAttribute("news", news);
        model.addAttribute("owner", userService.getUser(news.getUserId()));
        return "detail";
    }

6.HTML: detail.html

#parse("header.html")
<div id="main">
    <div class="container">
        <div class="post detail">

            <div class="votebar">
                #if($like>0)
                <button class="click-like up pressed" data-id="$!{news.id}" title="赞同"><i class="vote-arrow"></i><span class="count">$!{news.likeCount}</span></button>
                #else
                <button class="click-like up" data-id="$!{news.id}" title="赞同"><i class="vote-arrow"></i><span class="count">$!{news.likeCount}</span></button>
                #end
                #if($like<0)
                <button class="click-dislike down pressed" data-id="$!{news.id}" title="反对"><i class="vote-arrow"></i></button>
                #else
                <button class="click-dislike down" data-id="$!{news.id}" title="反对"><i class="vote-arrow"></i></button>
                #end
            </div>

            <div class="content">
                <div class="content-img">
                    <img src="$!{news.image}" >
                </div>
                <div class="content-main">
                    <h3 class="title">
                        <a target="_blank" rel="external nofollow" href="$!{news.link}">$!{news.title}</a>
                    </h3>
                    <div class="meta">
                        $!{news.link}
                              <span>
                                  <i class="fa icon-comment"></i> $!{news.commentCount}
                              </span>
                    </div>
                </div>
            </div>
            <div class="user-info">
                <div class="user-avatar">
                    <a href="/user/$!{owner.id}"><img width="32" class="img-circle" src="$!{owner.headUrl}"></a>
                </div>

            </div>

            <div class="subject-name">来自 <a href="/user/$!{owner.id}">$!{owner.name}</a></div>
        </div>

        <div class="post-comment-form">
            #if($user)
            <span>评论 ($!{news.commentCount})</span>
            <form method="post" action="/addComment">
                <input name="newsId" type="hidden" value="$!{news.id}">

                <div class="form-group text required comment_content">
                    <label class="text required sr-only">
                        <abbr title="required">*</abbr> 评论</label>
                    <textarea rows="5" class="text required comment-content form-control" name="content" id="content"></textarea>
                </div>
                <div class="text-right">
                    <input type="submit" name="commit" value="提 交" class="btn btn-default btn-info">
                </div>
            </form>
            #else
            <div class="login-actions">
                <a class="btn btn-success" href="/?pop=1">登录后评论</a>
            </div>
            #end
        </div>

        <div id="comments" class="comments">
            #foreach($commentvo in $comments)
            <div class="media">
                <a class="media-left" href="/user/$!{commentvo.user.id}">
                    <img src="$!{commentvo.user.headUrl}">
                </a>
                <div class="media-body">
                    <h4 class="media-heading">
                        <small class="date">$date.format(‘yyyy-MM-dd HH:mm:ss‘, $!{commentvo.comment.createdDate})
                        </small>
                    </h4>
                    <div>$!{commentvo.comment.content}</div>
                </div>
            </div>
            #end
        </div>

    </div>
    <script type="text/javascript">
          $(function(){

            // If really is weixin
            $(document).on(‘WeixinJSBridgeReady‘, function() {

              $(‘.weixin-qrcode-dropdown‘).show();

              var options = {
                "img_url": "",
                "link": "http://nowcoder.com/j/wt2rwy",
                "desc": "",
                "title": "读《Web 全栈工程师的自我修养》"
              };

              WeixinJSBridge.on(‘menu:share:appmessage‘, function (argv){
                WeixinJSBridge.invoke(‘sendAppMessage‘, options, function (res) {
                  // _report(‘send_msg‘, res.err_msg)
                });
              });

              WeixinJSBridge.on(‘menu:share:timeline‘, function (argv) {
                WeixinJSBridge.invoke(‘shareTimeline‘, options, function (res) {
                  // _report(‘send_msg‘, res.err_msg)
                });
              });

              // $(window).on(‘touchmove scroll‘, function() {
              //   if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
              //     $(‘div.backdrop‘).show();
              //     $(‘div.share-help‘).show();
              //   } else {
              //     $(‘div.backdrop‘).hide();
              //     $(‘div.share-help‘).hide();
              //   }
              // });

            });

          })

    </script>
    <script type="text/javascript" src="/scripts/main/site/detail.js"></script>
</div>
#parse("footer.html")
时间: 2024-08-11 09:27:59

6_1_评论中心的相关文章

EMLOG首页调用评论发布框和评论列表

在用EMLOG建设单页网站时,需要在首页显示评论发布框和评论列表,要实现这个功能,就需要修改模版脚本文件module.php里的blog_comments_post.blog_comments.blog_comments_children这三个函数来实现效果:默认情况下这三个函数需要在文章页面才能正常使用,因为这三个函数都绑定了文章ID号,首页没有文章ID号输入功能,所以我们如果想要在首页显示评论发布框和评论列表可以采用下面的方法来实现: 第一步: 在后台新建个单页,命名为评论中心,记住这个单页

管理信息系统 课程设计(2018-6-16)

1. 引言  在这个信息技术发展飞快的时代,信息也不再是像从前那么单一,具体的形式来存在的,所以我们对于信息也不能以以前的态度去面对,我们要有更好的方法去管理信息,利用Python+Flask+MysqL和HTML+CSS去制作一个属于自己的网站,把信息进行统一的管理,才会跟上时代,不断进步. 在网络技术不断的发展之下,一些网页布局与后端链接有了更多的模式,特别是在网络上的管理信息系统的不断优化,这一模型概念也有了紧跟大局的改变.我们要学会挖掘其中的功能和优点.本次课程设计我主要是设计一个方便大

2018最新Java实战开发今日头条资讯网站

==================课程目录=====================第1节 开发工具和Java语言介绍主要介绍项目所需要的开发工具,并且会简单回顾这个项目所用到的语言-java,语法基础,控制流,数据结构,面向对象,异常,随机数等. 第2节 Spring入门和模板语法主要结合Spring进行入门介绍,包括参数解析,HTTP Method,AOP等等. 第3节 数据库交互iBatis集成 主要对业务的字段进行设计,数据库的创建,数据库的交互等,并会介绍注解和XML定义以及首页的开

新商业云:阿里云智能总裁张建锋首次亮相的信号

2019,将是数字化转型的加速之年,由消费者驱动的商业模式变革,将持续而深入的发生.根据Gartner 2019年首席信息官议程调查,亚太区的数字化业务正从初步试点迈入大规模应用,而通过数字渠道增加客户互动是亚太区数字化转型进入扩展阶段的主要推动因素.Gartner调查显示,47%的亚太地区CIO表示其所在企业已经更改了业务模式或者正在更改过程之中:40%的亚太地区CIO表示,不断变化的消费者需求正在推动其业务模式的转变. 但正如iPhone带来的移动商业变革那样,数字化转型并不意味着简单把PC

评论列表显示及排序,个人中心显示

显示所有评论{% for foo in ques.comments %} <ul class="list"> {% for foo in ques.comments %} <li class="post_item"> <a href="{{ url_for('usercenter',user_id=foo.author.id) }}" class="light">{{foo.author.u

SDN与NFV技术在云数据中心的规模应用探讨

Neo 2016-1-29 | 发表评论 编者按:以云数据中心为切入点,首先对SDN领域中的叠加网络.SDN控制器.VxLAN 3种重要技术特点进行了研究,接下来对NFV领域中的通用服务器性能.服务链两类关键问题展开具体分析.最后,阐述了前期开展的SDN/NFV技术试验工 作进展及相关结论,并对VDC应用产品进行了展望. 1 引言 伴随着云计算技术的兴起,数据趋于大集中,传统电信系统网络架构成为阻碍云数据中心发展的巨大桎梏.为满足数据中心在云计算环境下的虚拟网络资源调度和共享需求,未来的数据中心

京东评论情感分类器(基于bag-of-words模型)

最近在本来在研究paraVector模型,想拿bag-of-words来做对比. 数据集是京东的评论,经过人工挑选,选出一批正面和负面的评论. 实验的数据量不大,340条正面,314条负面.我一般拿200正面和200负面做训练,剩下做测试. 做着做着,领悟了一些机器学习的道理.发现,对于不同的数据集,效果是不同的. 对于特定的数据集,随便拿来一套模型可能并不适用. 对于这些评论,我感觉就是bag-of-words模型靠谱点. 因为这些评论的特点是语句简短,关键词重要. paraVector模型感

以用户为中心的前端设计案例剖析

WEB前端设计的最终目标是打造用户喜爱的产品,属于产品设计的范畴.所以一切设计要以用户为出发点,追求最佳的用户体验. 一.banner的设计 在WEB项目设计中,我们经常会有banner设计需求,一般而言首屏Banner及其相关区域也是整个网页设计中非常重要的部分. 优化前: 优化后: 优化前: 1.优化前网页首屏图片自动切换交互方式之外,用户可以点击圆点按钮手动切换图片.但考虑到图片本身的展示空间和效果,圆点按钮设计的比较小,造成用户点击该按钮时不方便. 2.banner切换图片时,会存在图片

博客项目实现文章评论功能(重点是评论回复)

我开发的博客网站的地址:http://118.89.29.170/RiXiang_blog/ 博客项目代码github:https://github.com/SonnAdolf/sonne_blog 有了我的已成型的项目和代码,可以更容易理解这篇文章. 本篇文章记录下自己博客项目评论功能实现的全过程,重点其实是评论回复功能. [一,写评论] 写评论部分我没有使用富文本编辑器,只是单纯地使用了textarea标签,所以后台不需要作html标签的白名单检验(关于防范xss攻击,可以看我之前的一篇文章