栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

牛客网项目——项目开发(四):发布帖子,帖子详情,显示评论,添加评论

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

牛客网项目——项目开发(四):发布帖子,帖子详情,显示评论,添加评论

文章目录
  • 1. 过滤敏感词
    • 1.1 前缀树
    • 1.2 代码实现
  • 2. 发布帖子
    • 2.1 编写工具类传输json数据
    • 2.2 AJAX示例
    • 2.3 实现发布帖子功能
      • 2.3.1 数据访问层
      • 2.3.2 业务层
      • 2.3.3 视图层
  • 3. 帖子详情
    • 3.1 数据访问层
    • 3.2 业务层
    • 3.3 表现层
    • 3.4 前端页面
  • 5. 显示评论
    • 5.1 数据访问层
      • 5.1.1 数据库中的评论表
      • 5.1.2 entity下实现实体类 Comment
      • 5.1.3 dao下实现接口 CommentMapper
      • 5.1.4 mapper下实现comment-mapper.xml
    • 5.2 业务层
    • 5.3 表现层
      • 5.3.1 补充DiscussPostController
      • 5.3.2 处理index.html
      • 5.3.3 处理discuss-detail.html
  • 6. 添加评论
    • 6.1 数据访问层
    • 6.2 业务层
    • 6.3 表现层
      • 6.3.1 新建CommentController
      • 6.3.2 处理descuss-detail.xml

1. 过滤敏感词

1.1 前缀树

1.2 代码实现

在resources下新建sensitive-word.txt,并在util下实现 SensitiveFilter

  1. 定义前缀树结构
	// 前缀树
    private class TrieNode {

        // 关键词结束标识
        private boolean isKeywordEnd = false;

        // 子节点(key是下级字符,value是下级节点)
        private Map subNodes = new HashMap<>();

        public boolean isKeywordEnd() {
            return isKeywordEnd;
        }

        public void setKeywordEnd(boolean keywordEnd) {
            isKeywordEnd = keywordEnd;
        }

        // 添加子节点
        public void addSubNode(Character c, TrieNode node) {
            subNodes.put(c, node);
        }

        // 获取子节点
        public TrieNode getSubNode(Character c) {
            return subNodes.get(c);
        }

    }
  1. 敏感词添加到前缀树方法
 	// 将一个敏感词添加到前缀树中
    private void addKeyword(String keyword) {
        TrieNode tempNode = rootNode;
        for (int i = 0; i < keyword.length(); i++) {
            char c = keyword.charAt(i);
            TrieNode subNode = tempNode.getSubNode(c);

            if (subNode == null) {
                // 初始化子节点
                subNode = new TrieNode();
                tempNode.addSubNode(c, subNode);
            }

            // 指向子节点,进入下一轮循环
            tempNode = subNode;

            // 设置结束标识
            if (i == keyword.length() - 1) {
                tempNode.setKeywordEnd(true);
            }
        }
    }
  1. 初始化方法
	@PostConstruct
    public void init() {
        try (
                InputStream is = this.getClass().getClassLoader().getResourceAsStream("sensitive-words.txt");
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        ) {
            String keyword;
            while ((keyword = reader.readLine()) != null) {
                // 添加到前缀树
                this.addKeyword(keyword);
            }
        } catch (IOException e) {
            logger.error("加载敏感词文件失败: " + e.getMessage());
        }
    }
  1. 过滤敏感词方法
	
    public String filter(String text) {
        if (StringUtils.isBlank(text)) {
            return null;
        }

        // 指针1
        TrieNode tempNode = rootNode;
        // 指针2
        int begin = 0;
        // 指针3
        int position = 0;
        // 结果
        StringBuilder sb = new StringBuilder();

        while (position < text.length()) {
            char c = text.charAt(position);

            // 跳过符号
            if (isSymbol(c)) {
                // 若指针1处于根节点,将此符号计入结果,让指针2向下走一步
                if (tempNode == rootNode) {
                    sb.append(c);
                    begin++;
                }
                // 无论符号在开头或中间,指针3都向下走一步
                position++;
                continue;
            }

            // 检查下级节点
            tempNode = tempNode.getSubNode(c);
            if (tempNode == null) {
                // 以begin开头的字符串不是敏感词
                sb.append(text.charAt(begin));
                // 进入下一个位置
                position = ++begin;
                // 重新指向根节点
                tempNode = rootNode;
            } else if (tempNode.isKeywordEnd()) {
                // 发现敏感词,将begin~position字符串替换掉
                sb.append(REPLACeMENT);
                // 进入下一个位置
                begin = ++position;
                // 重新指向根节点
                tempNode = rootNode;
            } else {
                // 检查下一个字符
                position++;
            }
        }

        // 将最后一批字符计入结果
        sb.append(text.substring(begin));

        return sb.toString();
    }
2. 发布帖子

2.1 编写工具类传输json数据
  1. 导入依赖fastjson
		
			com.alibaba
			fastjson
			1.2.58
		
  1. 在CommunityUtil下添加方法
    ① 服务器给浏览器返回编码(code),比如0代表什么意思,1代表什么意思
    ② 服务器给浏览器返回提示信息(msg),成果或失败
    ③ 还可能返回业务数据(map)
    public static String getJSONString(int code, String msg, Map map) {
        JSONObject json = new JSONObject();
        json.put("code", code);
        json.put("msg", msg);
        if (map != null) {
            for (String key : map.keySet()) {
                json.put(key, map.get(key));
            }
        }
        return json.toJSONString();
    }

④ 参数可能不是都有,重载

	public static String getJSONString(int code, String msg) {
        return getJSONString(code, msg, null);
    }

    public static String getJSONString(int code) {
        return getJSONString(code, null, null);
    }

⑤ 写个main方法简单测一下,不需要容器管理

    public static void main(String[] args) {
        Map map = new HashMap<>();
        map.put("name", "zhangsan");
        map.put("age", 25);
        System.out.println(getJSONString(0, "ok", map));
    }

2.2 AJAX示例
  1. 在AlphaController里编写示例方法 testAjax
    // ajax示例
    @RequestMapping(path = "/ajax", method = RequestMethod.POST)
    @ResponseBody
    public String testAjax(String name, int age) {
        System.out.println(name);
        System.out.println(age);
        return CommunityUtil.getJSONString(0, "操作成功!");
    }
  1. 编写一个静态网页测试
    ① 引入jquery
    ② 实现post请求



    
    AJAX


    


点击发送后

2.3 实现发布帖子功能 2.3.1 数据访问层
  1. 在DiscussPostMapper中增加插入帖子数据方法
int insertDiscussPost(DiscussPost discussPost);
  1. 修改discusspost-mapper.xml

    user_id, title, content, type, status, create_time, comment_count, score



    insert into discuss_post()
    values(#{userId},#{title},#{content},#{type},#{status},#{createTime},#{commentCount},#{score})

2.3.2 业务层
  1. 在DiscussPostService添加方法addDiscussPost
    ① 判断内容空
    ② 发布的文字进行转义,包括标签和内容
    ③ 过滤敏感词
@Autowired
private DiscussPostMapper discussPostMapper;

@Autowired
private SensitiveFilter sensitiveFilter;

public int addDiscussPost(DiscussPost post) {
	if (post == null) {
	    throw new IllegalArgumentException("参数不能为空!");
	}
	
	// 转义HTML标记
	post.setTitle(HtmlUtils.htmlEscape(post.getTitle()));
	post.setContent(HtmlUtils.htmlEscape(post.getContent()));
	// 过滤敏感词
	post.setTitle(sensitiveFilter.filter(post.getTitle()));
	post.setContent(sensitiveFilter.filter(post.getContent()));
	
	return discussPostMapper.insertDiscussPost(post);
}
2.3.3 视图层
  1. 新建DiscussPostController,实现addDiscussPost
    ① 判断当前是否登录,没登陆返回code:403
    ② 创建post对象。存入信息,发布成功返回code:0
@RequestMapping(path = "/add", method = RequestMethod.POST)
@ResponseBody
public String addDiscussPost(String title, String content) {
	User user = hostHolder.getUser();
	if (user == null) {
	    return CommunityUtil.getJSONString(403, "你还没有登录哦!");
	}
	
	DiscussPost post = new DiscussPost();
	post.setUserId(user.getId());
	post.setTitle(title);
	post.setContent(content);
	post.setCreateTime(new Date());
	discussPostService.addDiscussPost(post);
	
	// 报错的情况,将来统一处理.
	return CommunityUtil.getJSONString(0, "发布成功!");
}
  1. 处理页面
    ① 处理index.js
$(function(){
	$("#publishBtn").click(publish);
});

function publish() {
	$("#publishModal").modal("hide");

	// 获取标题和内容
	var title = $("#recipient-name").val();
	var content = $("#message-text").val();
	// 发送异步请求(POST)
	$.post(
	    CONTEXT_PATH + "/discuss/add",
	    {"title":title,"content":content},
	    function(data) {
	        data = $.parseJSON(data);
	        // 在提示框中显示返回消息
	        $("#hintBody").text(data.msg);
	        // 显示提示框
            $("#hintModal").modal("show");
            // 2秒后,自动隐藏提示框
            setTimeout(function(){
                $("#hintModal").modal("hide");
                // 刷新页面
                if(data.code == 0) {
                    window.location.reload();
                }
            }, 2000);
	    }
	);

}

② 不登陆不显示发布的按钮 index.html,判断当前是否有用户登录即可


3. 帖子详情

3.1 数据访问层
  1. 在DiscussPostMapper中添加查询帖子方法
DiscussPost selectDiscussPostById(int id);
  1. 在discusspost-mapper.xml 下添加方法

        select 
        from comment
        where status = 0
        and entity_type = #{entityType}
        and entity_id = #{entityId}
        order by create_time asc
        limit #{offset}, #{limit}
    

    


5.2 业务层

service下实现 CommentService

package com.nowcoder.community.service;

import com.nowcoder.community.dao.CommentMapper;
import com.nowcoder.community.entity.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CommentService implements CommunityConstant {

    @Autowired
    private CommentMapper commentMapper;


    public List findCommentsByEntity(int entityType, int entityId, int offset, int limit) {
        return commentMapper.selectCommentsByEntity(entityType, entityId, offset, limit);
    }

    public int findCommentCount(int entityType, int entityId) {
        return commentMapper.selectCountByEntity(entityType, entityId);
    }
}

5.3 表现层 5.3.1 补充DiscussPostController
  1. 注入CommentService
  2. 借助分页,参数添加page
  3. 设置评论分页信息,每页显示5条,设置路径,一共有多少评论数据
    page.setLimit(5); page.setPath("/discuss/detail/" + discussPostId); page.setRows(post.getCommentCount());
  4. 得到当前帖子的所有评论 List commentList
  5. 遍历评论集合,创建评论VO列表,并放入map封装数据
    1. 放入评论内容 commentVo.put("comment", comment);
    2. 放入作者信息 commentVo.put("user", userService.findUserById(comment.getUserId()));
    3. 放入回复列表 List replyList
    4. 创建回复的VO列表,还是map List> replyVoList
      1. 放入回复内容 replyVo.put("reply", reply);
      2. 放入恢复者名字 replyVo.put("user", userService.findUserById(reply.getUserId()));
      3. 放入回复的目标(先判0)replyVo.put("target", target);
      4. replyVoList 放入commentVo commentVo.put("replys", replyVoList);
    5. 放入回复的数量 commentVo.put("replyCount", replyCount);
    6. commentVo 放入commentVoList commentVoList.add(commentVo);
  6. 最后comment翻入model model.addAttribute("comments", commentVoList);
@Autowired
private CommentService commentService;

@RequestMapping(path = "/detail/{discussPostId}", method = RequestMethod.GET)
public String getDiscussPost(@PathVariable("discussPostId") int discussPostId, Model model, Page page) {
    // 帖子
    DiscussPost post = discussPostService.findDiscussPostById(discussPostId);
    model.addAttribute("post", post);
    // 作者
    User user = userService.findUserById(post.getUserId());
    model.addAttribute("user", user);

    // 评论分页信息
    page.setLimit(5);
    page.setPath("/discuss/detail/" + discussPostId);
    page.setRows(post.getCommentCount());

    // 评论: 给帖子的评论
    // 回复: 给评论的评论
    // 评论列表
    List commentList = commentService.findCommentsByEntity(
            ENTITY_TYPE_POST, post.getId(), page.getOffset(), page.getLimit());
    // 评论VO列表
    List> commentVoList = new ArrayList<>();
    if (commentList != null) {
        for (Comment comment : commentList) {
            // 评论VO
            Map commentVo = new HashMap<>();
            // 评论
            commentVo.put("comment", comment);
            // 作者
            commentVo.put("user", userService.findUserById(comment.getUserId()));

            // 回复列表
            List replyList = commentService.findCommentsByEntity(
                    ENTITY_TYPE_COMMENT, comment.getId(), 0, Integer.MAX_VALUE);
            // 回复VO列表
            List> replyVoList = new ArrayList<>();
            if (replyList != null) {
                for (Comment reply : replyList) {
                    Map replyVo = new HashMap<>();
                    // 回复
                    replyVo.put("reply", reply);
                    // 作者
                    replyVo.put("user", userService.findUserById(reply.getUserId()));
                    // 回复目标
                    User target = reply.getTargetId() == 0 ? null : userService.findUserById(reply.getTargetId());
                    replyVo.put("target", target);

                    replyVoList.add(replyVo);
                }
            }
            commentVo.put("replys", replyVoList);

            // 回复数量
            int replyCount = commentService.findCommentCount(ENTITY_TYPE_COMMENT, comment.getId());
            commentVo.put("replyCount", replyCount);

            commentVoList.add(commentVo);
        }
    }

    model.addAttribute("comments", commentVoList);

    return "/site/discuss-detail";
}
5.3.2 处理index.html

回帖数量

  • 回帖 7
  • 5.3.3 处理discuss-detail.html
    1. 回帖数量
    30条回帖
    1. 处理帖子展现,循环语句
    1. 作者头像
    用户头像
    
    1. 用户名字
    掉脑袋切切
    
    1. 一楼二楼
    	1#
    
    
    1. 处理回复,遍历
    1. 无目标回复,就是显示用户名
    	寒江雪:  
    
    
    1. 有目标回复,显示谁回复了谁
    	Sissi 回复
    	寒江雪:  
    
    
    1. 回复时间
    2019-04-15 15:32:18
    
    1. 点击回复时显示回复框
  • 回复
    1. 分页逻辑复用首页分页逻辑
      首页的
    
    

    当前页面的

    
    
    6. 添加评论

    1. 在 CommentMapper 增加方法 insertComment
    int insertComment(Comment comment);
    
    1. 在comment-mapper.xml 中实现语句
    
        user_id, entity_type, entity_id, target_id, content, status, create_time
    
    
    
        insert into comment()
        values(#{userId},#{entityType},#{entityId},#{targetId},#{content},#{status},#{createTime})
    
    
    6.1 数据访问层
    1. 在 CommentMapper 增加方法 insertComment
    int insertComment(Comment comment);
    
    1. 在comment-mapper.xml 中实现语句
    
        user_id, entity_type, entity_id, target_id, content, status, create_time
    
    
    
        insert into comment()
        values(#{userId},#{entityType},#{entityId},#{targetId},#{content},#{status},#{createTime})
    
    
    1. 更新帖子评论数量,在DiscussPostMapper增加updateCommentCount
    int updateCommentCount(int id, int commentCount);
    
    1. 更新帖子评论数量,更新对应的xml文件
    
        update discuss_post set comment_count = #{commentCount} where id = #{id}
    
    
    6.2 业务层
    1. 在DisscusPostService中添加方法updateCommentCount
    public int updateCommentCount(int id, int commentCount) {
        return discussPostMapper.updateCommentCount(id, commentCount);
    }
    
    1. 在CommentService中添加addComment,事务隔离
    @Autowired
    private DiscussPostService discussPostService;
    
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public int addComment(Comment comment) {
        if (comment == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }
    
        // 添加评论
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        comment.setContent(sensitiveFilter.filter(comment.getContent()));
        int rows = commentMapper.insertComment(comment);
    
        // 更新帖子评论数量
        if (comment.getEntityType() == ENTITY_TYPE_POST) {
            int count = commentMapper.selectCountByEntity(comment.getEntityType(), comment.getEntityId());
            discussPostService.updateCommentCount(comment.getEntityId(), count);
        }
    
        return rows;
    }
    
    6.3 表现层 6.3.1 新建CommentController
    package com.nowcoder.community.controller;
    
    import com.nowcoder.community.entity.Comment;
    import com.nowcoder.community.service.CommentService;
    import com.nowcoder.community.util.HostHolder;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    import java.util.Date;
    
    @Controller
    @RequestMapping("/comment")
    public class CommentController {
    
        @Autowired
        private CommentService commentService;
    
        @Autowired
        private HostHolder hostHolder;
    
        @RequestMapping(path = "/add/{discussPostId}", method = RequestMethod.POST)
        public String addComment(@PathVariable("discussPostId") int discussPostId, Comment comment) {
            comment.setUserId(hostHolder.getUser().getId());
            comment.setStatus(0);
            comment.setCreateTime(new Date());
            commentService.addComment(comment);
    
            return "redirect:/discuss/detail/" + discussPostId;
        }
    
    }
    
    
    6.3.2 处理descuss-detail.xml
    1. 最底下针对帖子的评论
      ① 提交表单

    ② 处理文本域,取名为content和实体属性对应

    
    

    ③ 两个隐含条件entityType和entityId

    
    
    
    1. 给一个评论进行回复(不针对某个人)
      ① 完成表单
    
    	……
    
    

    ② 处理文本域,取名为content和实体属性对应

    
    

    ③ 两个隐含条件entityType和entityId

    
    
    
    1. 给一个评论进行回复(对某个人)
      ① 完成表单
    ……

    ② 处理文本域,取名为content和实体属性对应

    
    

    ③ 两个隐含条件entityType和entityId和targetId

    
    
    
    

    ④ 显示回复给哪个人

    
    
    转载请注明:文章转载自 www.mshxw.com
    本文地址:https://www.mshxw.com/it/914709.html
    我们一直用心在做
    关于我们 文章归档 网站地图 联系我们

    版权所有 (c)2021-2022 MSHXW.COM

    ICP备案号:晋ICP备2021003244-6号