我开发的博客网站的地址:http://118.89.29.170/RiXiang_blog/
博客项目代码github:https://github.com/SonnAdolf/sonne_blog
有了我的已成型的项目和代码,可以更容易理解这篇文章。
本篇文章记录下自己博客项目评论功能实现的全过程,重点其实是评论回复功能。
【一,写评论】
写评论部分我没有使用富文本编辑器,只是单纯地使用了textarea标签,所以后台不需要作html标签的白名单检验(关于防范xss攻击,可以看我之前的一篇文章http://www.cnblogs.com/rixiang/p/6239464.html),只需要将所有<和>字符作转义即可。
提交到后台需要做的处理:必要的校验,存储。然后生成消息。消息会在用户个人空间消息中心显示。提示用户有新的评论。
数据库存储方面,评论与文章的关系是双向多对一。设置懒加载和级联删除。
写评论部分就这些,没什么好说的。
【二,评论显示】
评论的显示是基于文章的。也就是说在点击、查看一篇文章的同时,在该文章下面显示对这篇文章的所有评论。
上面提到评论和文章是多对一的关系,可知,查询到文章即可查询到该文章的所有评论。也正因此,且鉴于自己博客评论数并不很多情况,对于评论的分页我没有采用数据库查询层的分页方法,而是用java写了分页、排序。我并不确定最好的实现。
/* * Select the article by the id, and show it at the jsp page. * * @param HttpServletRequest request, Integer id, Model model * * @return the jsp page */ @RequestMapping(value = "/show", method = RequestMethod.GET) public String showFromMainPage(HttpServletRequest request, Integer id, Integer currentPage, Model model) throws Exception { if (null == id) { return "error"; } Article article = articleService.find(id, Article.class); // click the link, then read_times ++ article.setRead_times(article.getRead_times() + 1); articleService.update(article); article = getArticleOfContentByUrl(article); // sort the comments List<Comment> comments = commentService.sort(article.getComments()); String username = userService.getUsernameFromSession(request); model.addAttribute("article", article); model.addAttribute("username", username); model.addAttribute("article_id", id);