从零开始搭建自己的网站二十二:网站评论留言功能

现在评论的插件有挺多,引入的话也是比较简单的。我这里是自己开发一个评论功能,存入自己的数据库中,效果如下面所示。

undefined

首先表结构

undefined

主要的逻辑都是在JS中进行处理,对提交的评论内容进行拼接到页面,后台负责对提交的评论内容进行存入和查询。下面是JS代码

$(function () {
    $('.emotion').qqFace({        id: 'facebox',        assign: 'comment-textarea',        path: '/images/arclist/'	//表情存放的路径
    });    //评论替换表情
    $(".comment-content-detail").each(function () {        var str = this.innerText;
        $(this).html(replace_em(str));
    });
    
    $(this).find(".reply-btn").on("click",function () {        if ($(this).parent().parent().find(".reply-box").length > 0) {
            $(".reply-box").remove();
        } else {
            $(".reply-box").remove();
            replyClick($(this));
        }
    });
});//回复功能function createReplyComment(reply) {    var replyEl = "<div class='reply'><div><a href='javascript:void(0)' class='replyname'>" + reply.replyName + "</a>:<span>" + reply.content + "</span></div>"
        + "<div class='replyTime'><span>" + reply.time + "</span></div></div>";    return replyEl;
}//获取时间function getNowDateFormat() {    var nowDate = new Date();    var year = nowDate.getFullYear();    var month = filterNum(nowDate.getMonth() + 1);    var day = filterNum(nowDate.getDate());    var hours = filterNum(nowDate.getHours());    var min = filterNum(nowDate.getMinutes());    var seconds = filterNum(nowDate.getSeconds());    return year + "-" + month + "-" + day + " " + hours + ":" + min + ":" + seconds;
}function filterNum(num) {    if (num < 10) {        return "0" + num;
    } else {        return num;
    }
}//点击回复评论方法function replyClick(el) {
    el.parent().parent().append("<div class='reply-box'><textarea cols='100%' rows='3' tabindex='1' placeholder='来说几句吧~' class='mytextarea'></textarea><span class='send'>发送</span></div>").find(".send").click(function () {        var content = $(this).prev().val();        if (content != "") {            var parentEl = $(this).parent().parent().parent();            var obj = {};
            obj.replyName = "匿名";            // obj.beReplyName = parentEl.find(".comment-name").text();
            obj.pid = parentEl.find(".comment-name").attr("commentId");
            obj.content = content;
            obj.time = getNowDateFormat();
            obj.articleId = $('#articleId').val();            var replyString = createReplyComment(obj);
            $(".reply-box").remove();
            el.parent().parent().append(replyString);
            replyComment(obj);
        } else {
            alert("请输入内容");
        }
    });
}//提交评论function replyComment(comment){
    $.ajax({        type: "POST",        url: "/comment",        data: comment,        cache: false, //不缓存此页面
        success: function (data) {

        }
    });
}/*文章评论*/$(function () {
    $("#comment-submit").click(function () {        var commentContent = $("#comment-textarea");        var commentButton = $("#comment-submit");        var promptBox = $('.comment-prompt');        var promptText = $('.comment-prompt-text');
        promptBox.fadeIn(400);        if (commentContent.val() == '') {
            promptText.text('请留下您的评论');            return false;
        }        if (commentContent.val().length > 200) {
            promptText.text('评论长度不能超过200');            return false;
        }
        commentButton.attr('disabled', true);
        commentButton.addClass('disabled');
        promptText.text('正在提交...');
        $.ajax({            type: "POST",            url: "/comment",            data: $("#comment-form").serialize(),            cache: false, //不缓存此页面
            success: function (data) {                var comment = {};
                comment.replyName = "匿名";
                comment.time = getNowDateFormat();
                comment.count = $('.comment-content').length +1;
                comment.content = replace_em(commentContent.val());
                promptText.text('评论成功!');
                $(".commentlist").fadeIn(300);                /*$(".commentlist").append();*/
                commentButton.attr('disabled', false);
                commentButton.removeClass('disabled');
                $(".commentlist").append(appendComment(comment));
                commentContent.val(null);
            }
        });
        promptBox.fadeOut(100);        return false;
    });
});//拼接评论function appendComment(comment) {    var time = getNowDateFormat();    var con = "<li class='comment-content'><span class='comment-f'>#"
        + comment.count +"</span><div class='comment-avatar'><img class='avatar' src='../images/icon/icon.png' alt=''/></div><div class='comment-main'>" +        "<p>来自<span class='comment-name'>"+ comment.replyName +"</span>的用户<span class='time'>(" + comment.time + ")</span><br/>" +
        comment.content + "</p><div class='comment-reply'><div class='comment-replyIp col-md-10'><span></span></div><div class='col-md-2 reply-btn'><span>回复</span></div></div></div></li>";    return con;
}//对文章内容进行替换function replace_em(str) {
    str = str.replace(/\</g, '&lt;');
    str = str.replace(/\>/g, '&gt;');
    str = str.replace(/\[em_([0-9]*)\]/g, '<img src="/images/arclist/$1.gif" border="0" />');    return str;
}

对于评论我只设置了一层的回复,在Java代码中进行这样的处理。

实体类加了一个字段List<Comment>用来存放回复内容。

//实体类public class Comment {    //id
    private int id;    //内容
    private String content;    //文章ID
    private int articleId;    //时间
    private String date;    //评论人IP
    private String commentIp;    //PID
    private int pid;    //用户名称
    private String commentName;    //用户ID
    private int commentId;    //子回复
    private List<Comment> comments;

    .. set get ..
}

然后再service中进行处理

    @Override
    public List<Comment> findCommentByArticleId(int id) {
        List<Comment> commentList = commentDao.findCommentByArticleId(id);
        List<Comment> convert = convert(commentList);        return convert;
    }    /**
     * 转换评论方法,通过PID来进行关联
     *
     * @param list 评论数据
     */
    private List<Comment> convert(List<Comment> list) {
        List<Comment> comments = new ArrayList<>();        for (Comment comment : list) {            if (comment.getPid() == 0) {
                List<Comment> commentList = new ArrayList<>();                for (Comment commentChlid : list) {                    if (comment.getId() == commentChlid.getPid()) {
                        commentList.add(commentChlid);
                    }
                }
                comment.setComments(commentList);
                comments.add(comment);
            }
        }        return comments;
    }

在HTML页面上进行展示

<li class="comment-content"><span class="comment-f">#${comment_index+1}</span>
    <div class="comment-avatar">
        <img class="avatar" src="../images/icon/icon.png" alt=""/>
    </div>
    <div class="comment-main">
        <p>来自<span class="comment-name" commentId="${comment.id}">
            <#if comment.commentName?exists>${comment.commentName}<#else>匿名</#if>
        </span>的用户            <span class="time">(${comment.date})</span><br/>
        <div class="comment-content-detail">${comment.content}</div>
        </p>
        <div class="comment-reply">
            <div class="comment-replyIp col-md-10">
                <span>
                    <#if comment.commentIp?exists>
                        <i class="glyphicon glyphicon-pushpin">
                            ${comment.commentIp}                        </i>
                    </#if>
                </span>
            </div>
            <div class="col-md-2 reply-btn">
                <span>回复</span>
            </div>
        </div>
        <#if comment.comments?exists>
            <#list comment.comments as commentChild>
                <div class="reply">
                    <div>
                        <a href="javascript:void(0)" class="replyname">${commentChild.commentName}</a>:                       <span>${commentChild.content}</span>
                    </div>
                    <div class="replyTime">
                        <span>${commentChild.date}</span>
                    </div>
                </div>
            </#list>
        </#if>
    </div></li>


评论 抢沙发

表情
  1. #1

    来自 匿名 的用户 (2019-06-11 23:27:44)

    sadasd

    113.64.74.31
    回复
  2. #2

    来自 匿名 的用户 (2019-06-11 23:27:50)

    asdasd

    113.64.74.31
    回复
  3. #3

    来自 匿名 的用户 (2019-07-15 14:59:19)

    [em_65]

    222.88.236.172
    回复
Title