3.6添加评论

在这里插入图片描述

数据层

增加评论数据、修改帖子的评论数量

    int insertComment(Comment comment);
    在mapper.xml中
    <insert id="insertComment" parameterType="Comment">
        insert into comment(<include refid="insertFields"></include>)
        values(#{userId},#{entityType},#{entityId},#{targetId},#{content},#{status},#{createTime})
    </insert>

业务层


    //由于有两次事务操作,所以要进行事务管理,这里使用声明式事务
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
    public int addComment(Comment comment){
        if (comment == null){
            throw new IllegalArgumentException("参数不能为空");
        }

        //添加评论
        //先用htmlutil工具转义,然后才能使用工具类进行敏感词过滤
        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;
    }

表现层

@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;
    }
}

前端模板

理清楚对应的逻辑,这里的post.id会直接传到controller中作为discussPostId使用,其次,基于同名原则,entityType和entityId会自动对应comment对象,然后controller层就可以更新数据了。

									<form method="post" th:action="@{|/comment/add/${post.id}|}">
										<div>
											<input type="text" class="input-size" name="content" placeholder="请输入你的观点"/>
											<input type="hidden" name="entityType" value="2">
											<input type="hidden" name="entityId" th:value="${cvo.comment.id}">
										</div>
										<div class="text-right mt-2">
											<button type="submit" class="btn btn-primary btn-sm" onclick="#">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</button>
										</div>

									</form>
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值