@jikeytang
2025-02-19T05:10:25.000000Z
字数 4913
阅读 304
2025-blog
在Spring Boot 2中实现回复评论的功能与Spring Boot 3的实现非常相似,主要区别在于Spring Boot 2的依赖管理和一些API的细微差异。以下是基于Spring Boot 2的实现步骤和代码示例。
创建一个Comment实体类来表示评论。
import javax.persistence.*;import java.util.ArrayList;import java.util.List;@Entitypublic class Comment {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private String content;@ManyToOne@JoinColumn(name = "parent_id")private Comment parent;@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true)private List<Comment> replies = new ArrayList<>();// Getters and Setterspublic Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}public Comment getParent() {return parent;}public void setParent(Comment parent) {this.parent = parent;}public List<Comment> getReplies() {return replies;}public void setReplies(List<Comment> replies) {this.replies = replies;}}
创建一个CommentRepository接口来操作数据库。
import org.springframework.data.jpa.repository.JpaRepository;import java.util.List;public interface CommentRepository extends JpaRepository<Comment, Long> {List<Comment> findByParentIsNull();}
创建一个CommentService来处理业务逻辑。
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;@Servicepublic class CommentService {@Autowiredprivate CommentRepository commentRepository;public List<Comment> getTopLevelComments() {return commentRepository.findByParentIsNull();}public Comment addComment(Comment comment) {return commentRepository.save(comment);}public Comment addReply(Long parentId, Comment reply) {Comment parent = commentRepository.findById(parentId).orElseThrow(() -> new RuntimeException("Parent comment not found"));reply.setParent(parent);return commentRepository.save(reply);}}
创建一个CommentController来处理HTTP请求。
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*;import java.util.List;@RestController@RequestMapping("/api/comments")public class CommentController {@Autowiredprivate CommentService commentService;@GetMappingpublic List<Comment> getComments() {return commentService.getTopLevelComments();}@PostMappingpublic Comment addComment(@RequestBody Comment comment) {return commentService.addComment(comment);}@PostMapping("/{parentId}/reply")public Comment addReply(@PathVariable Long parentId, @RequestBody Comment reply) {return commentService.addReply(parentId, reply);}}
前端的实现与Spring Boot 3的完全一致,因为前端不依赖于后端的具体版本。以下是简要步骤:
npm install element-plus
创建Comment.vue组件。
<template><div class="comment"><div class="comment-content">{{ comment.content }}</div><el-button type="text" @click="showReplyForm = !showReplyForm">回复</el-button><div v-if="showReplyForm"><el-input v-model="replyContent" placeholder="输入回复内容"></el-input><el-button type="primary" @click="submitReply">提交</el-button></div><div v-if="comment.replies && comment.replies.length > 0" class="replies"><Comment v-for="reply in comment.replies" :key="reply.id" :comment="reply"></Comment></div></div></template><script>export default {name: 'Comment',props: {comment: {type: Object,required: true}},data() {return {showReplyForm: false,replyContent: ''};},methods: {async submitReply() {const reply = {content: this.replyContent,parentId: this.comment.id};await this.$http.post(`/api/comments/${this.comment.id}/reply`, reply);this.showReplyForm = false;this.replyContent = '';this.$emit('reload');}}};</script><style scoped>.comment {margin-left: 20px;margin-top: 10px;}.replies {margin-left: 20px;}</style>
创建CommentList.vue组件。
<template><div><Comment v-for="comment in comments" :key="comment.id" :comment="comment" @reload="loadComments"></Comment><el-input v-model="newComment" placeholder="输入新评论"></el-input><el-button type="primary" @click="submitComment">提交</el-button></div></template><script>import Comment from './Comment.vue';export default {components: {Comment},data() {return {comments: [],newComment: ''};},async created() {this.loadComments();},methods: {async loadComments() {const response = await this.$http.get('/api/comments');this.comments = response.data;},async submitComment() {const comment = {content: this.newComment};await this.$http.post('/api/comments', comment);this.newComment = '';this.loadComments();}}};</script>
<template><div id="app"><CommentList></CommentList></div></template><script>import CommentList from './components/CommentList.vue';export default {components: {CommentList}};</script>
在main.js中配置HTTP请求。
import { createApp } from 'vue';import App from './App.vue';import ElementPlus from 'element-plus';import 'element-plus/lib/theme-chalk/index.css';import axios from 'axios';import VueAxios from 'vue-axios';const app = createApp(App);app.use(ElementPlus);app.use(VueAxios, axios);app.mount('#app');
确保后端Spring Boot 2应用已经启动,然后运行前端Vue项目。
npm run serve
在Spring Boot 2中实现回复评论的功能与Spring Boot 3的实现几乎一致,主要区别在于Spring Boot 2的依赖管理和一些API的细微差异。前端的实现完全通用,不依赖于后端的具体版本。你可以根据需要进一步扩展和优化这个功能。