Java评论,递归加载评论,嵌套评论

实体类:

public class Comment {

    private Integer id;
    private DownInfo downInfo;
    private String content;
    @JSONField(format = "yyyy-MM-dd hh:mm")   //FastJson包使用注解
    @JsonFormat(pattern="yyyy-MM-dd hh:mm",timezone="GMT+8")//Jackson包使用注解
    @DateTimeFormat(pattern="yyyy-MM-dd hh:mm")
    private Date time;
    private Comment parent;
    private List children; //回复集合

}

控制器:

//获取此资源的所有评论转换成json格式传出
@RequestMapping(value="/comments",produces="application/json;charset=UTF-8")
@ResponseBody
public String getCommentList(Integer rid){
    System.out.println("触发事件");
    List list = service.findListByResourceId(rid);
    SimplePropertyPreFilter filter = new      SimplePropertyPreFilter(Comment.class,"id","content","downInfo","time","children");
    SimplePropertyPreFilter filter2 = new SimplePropertyPreFilter(DownInfo.class,"id","score","member");
    SimplePropertyPreFilter filter3 = new SimplePropertyPreFilter(Member.class,"id","nickName");
    return JSONArray.toJSONString(list,new SimplePropertyPreFilter[]{filter,filter2,filter3});
}

//递归将此评论的所有回复评论添加到集合中,data集合中只有一个Comment
public List getList(List data){
    List list = new ArrayList();
    if(data==null || data.size()==0){return list;}
    for(int i=0;i
        list.add(data.get(i));
        list.addAll(getList(data.get(i).getChildren()));
    }
    return list;
}

 

  1. js编写

<script type="text/javascript">
    $(function () {
        loaddata();//加载评论数据
        function loaddata() {
            $.getJSON("${pageContext.request.contextPath}/comment/comments", {"rid": $("#source").attr("tag")}, function (data) {
                //console.log(data);
                $("#comments").empty().append(addComm(data));
            });
        }

        //模板
        var a = "回复";
        var current = $("#member").attr("tag");

        function addComm(data) {
            if (!data || data.length == 0) {
                return "";
            }
            var result = "";
            for (var i = 0; i < data.length; i++) {
                //模板
                var tmp = "

@name:        @content  @time    @a@child
"
                var c = data[i];
                if (c.downInfo.member.id == current) {//如果此条评论是本人发出,去掉回复按钮
                    tmp = tmp.replace("@a", "")
                } else {
                    tmp = tmp.replace("@a", a.replace("@val", c.id));
                }
                result += tmp.replace("@name", c.downInfo.member.nickName)
                    .replace("@content", c.content)
                    .replace("@time", c.time)
                    .replace("@child", addComm(c.children));
                console.log(result);
            }
            return result;
        }

        console.log(current + "当前用户");
script>

 

你可能感兴趣的:(Java评论,递归加载评论,嵌套评论)