============= 后端_添加评论 ============= 1 视图对象 1.1 评论参数视图对象 /ysdblog-api/src/main/java/com/weihome/ysdblog/vo/param/CommentParam.java: @Data public class CommentParam { private String content; private Long articleId; private Long parentId; private Long toUid; } 2 评论服务 2.1 评论服务接口 /ysdblog-api/src/main/java/com/weihome/ysdblog/service/CommentService.java: public interface CommentService { ... /** * 添加评论 */ Result add(CommentParam commentParam); ... } 2.2 评论服务实现 /ysdblog-api/src/main/java/com/weihome/ysdblog/service/impl/CommentServiceImpl.java: ... public class CommentServiceImpl implements CommentService { ... @Override public Result add(CommentParam commentParam) { Comment comment = new Comment(); comment.setContent(commentParam.getContent()); comment.setCreateDate(System.currentTimeMillis()); comment.setArticleId(commentParam.getArticleId()); comment.setAuthorId(UserThreadLocal.get().getId()); Long parentId = commentParam.getParentId(); comment.setParentId(parentId == null ? 0 : parentId); Long toUid = commentParam.getToUid(); comment.setToUid(toUid == null ? 0 : toUid); comment.setLevel(comment.getParentId() == 0 ? 1 : 2); commentMapper.insert(comment); return Result.success(null); } ... } 3 评论控制器 /ysdblog-api/src/main/java/com/weihome/ysdblog/controller/CommentController.java: ... public class CommentController { ... /** * 添加评论 */ @PostMapping("add") public Result add(@RequestBody CommentParam commentParam) { return commentService.add(commentParam); } ... } 4 添加登录拦截 /ysdblog-api/src/main/java/com/weihome/ysdblog/config/WebMvcConfig.java: ... public class WebMvcConfig implements WebMvcConfigurer { ... @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginInterceptor) ... .addPathPatterns("/comment/add") ... } ... } 5 运行测试 Postman POST localhost:8888/comment/add Headers Authorization: eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NDk2ODEyNzYsInVzZXJJZCI6MSwiaWF0IjoxNjQ4NzkyMjQzfQ.Ba9co3QLNvRJ3k2aYAN9zVvDliLl0KBTtTBfz1UkOgU Body { "content": "comment_a", "articleId": "1511577146642972674", "parentId": "0", "toUid": "0" } --------------------------- { "success": true, "code": 200, "msg": "success", "data": null } 检查数据库t_comment表中的新增记录。