数据层
增加评论数据、修改帖子的评论数量
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="#"> 回 复 </button>
</div>
</form>