首先设计评论表存储内容、作者、层级关系,再用Java实现Comment实体和DAO操作数据库,通过Servlet处理增删查请求,前端JSP展示并提交评论,支持嵌套回复功能。

开发一个小型论坛的评论功能,核心是实现用户发布、查看、回复和管理评论的能力。使用 Java 作为后端语言,配合数据库和简单的前端页面,就能快速搭建出基础功能。以下是关键步骤和代码示例。
评论功能需要存储评论内容、作者、发布时间以及层级关系(如回复)。可以设计一张 comments 表:
CREATE TABLE comments (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
content TEXT NOT NULL,
author VARCHAR(50) NOT NULL,
post_id INT NOT NULL, -- 所属帖子ID
parent_id BIGINT DEFAULT NULL, -- 回复的评论ID,为空表示一级评论
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX(post_id),
INDEX(parent_id)
);
其中 parent_id 实现嵌套回复:如果为 null,是一级评论;否则指向被回复的评论 ID。
创建对应的 Java 类和数据访问对象。
立即学习“Java免费学习笔记(深入)”;
Comment.java(实体类)
public class Comment {
private Long id;
private String content;
private String author;
private int postId;
private Long parentId;
private LocalDateTime createdAt;
<pre class='brush:java;toolbar:false;'>// 构造函数、getter、setter 省略}
CommentDAO.java(数据库操作)
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
<p>public class CommentDAO {
private Connection getConnection() throws SQLException {
return DriverManager.getConnection(
"jdbc:mysql://localhost:3306/forum", "root", "password");
}</p><pre class='brush:java;toolbar:false;'>// 获取某个帖子的所有评论(含回复)
public List<Comment> getCommentsByPostId(int postId) {
List<Comment> comments = new ArrayList<>();
String sql = "SELECT * FROM comments WHERE post_id = ? ORDER BY created_at ASC";
try (Connection conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, postId);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
Comment c = new Comment();
c.setId(rs.getLong("id"));
c.setContent(rs.getString("content"));
c.setAuthor(rs.getString("author"));
c.setPostId(rs.getInt("post_id"));
c.setParentId(rs.getLong("parent_id"));
c.setCreatedAt(rs.getTimestamp("created_at").toLocalDateTime());
comments.add(c);
}
} catch (SQLException e) {
e.printStackTrace();
}
return comments;
}
// 添加新评论
public boolean addComment(Comment comment) {
String sql = "INSERT INTO comments (content, author, post_id, parent_id) VALUES (?, ?, ?, ?)";
try (Connection conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, comment.getContent());
stmt.setString(2, comment.getAuthor());
stmt.setInt(3, comment.getPostId());
stmt.setObject(4, comment.getParentId()); // 允许 null
return stmt.executeUpdate() > 0;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}}
通过 Servlet 接收评论提交和展示请求。
凡诺企业网站管理系统是一个采用asp+access进行开发的asp企业网站源码。 十年企业建站老品牌值得信赖 凡诺企业网站管理系统后台功能简介: 1.无限级频道设置,自主指定频道类型。 2.完善的信息发布设置。 3.独立幻灯片设置 4.会员、留言、订单、评论、连接、内链一应俱全。 后台登陆地址:/admin/index.asp 管理员
0
AddCommentServlet.java
@WebServlet("/addComment")
public class AddCommentServlet extends HttpServlet {
private CommentDAO commentDAO = new CommentDAO();
<pre class='brush:java;toolbar:false;'>protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
req.setCharacterEncoding("UTF-8");
String content = req.getParameter("content");
String author = req.getParameter("author");
int postId = Integer.parseInt(req.getParameter("postId"));
String parentIdStr = req.getParameter("parentId");
Comment comment = new Comment();
comment.setContent(content);
comment.setAuthor(author);
comment.setPostId(postId);
if (parentIdStr != null && !parentIdStr.isEmpty()) {
comment.setParentId(Long.parseLong(parentIdStr));
}
if (commentDAO.addComment(comment)) {
resp.sendRedirect("viewPost.jsp?postId=" + postId);
} else {
resp.getWriter().println("评论失败");
}
}}
ViewCommentsServlet.java(可选API式返回)
也可以返回 JSON,便于前端动态加载。
@WebServlet("/api/comments")
public class ViewCommentsServlet extends HttpServlet {
private CommentDAO commentDAO = new CommentDAO();
<pre class='brush:java;toolbar:false;'>protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("application/json;charset=UTF-8");
int postId = Integer.parseInt(req.getParameter("postId"));
List<Comment> comments = commentDAO.getCommentsByPostId(postId);
// 简单手动转JSON(生产建议用Jackson/Gson)
StringBuilder json = new StringBuilder("[");
for (int i = 0; i < comments.size(); i++) {
Comment c = comments.get(i);
json.append(String.format(
"{\"id\":%d,\"author\":\"%s\",\"content\":\"%s\",\"parentId\":%s}",
c.getId(), c.getAuthor(), c.getContent(), c.getParentId()
));
if (i < comments.size() - 1) json.append(",");
}
json.append("]");
resp.getWriter().println(json.toString());
}}
简单 JSP 页面展示评论和输入框。
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<body>
<h2>评论区</h2>
<p><!-- 发表评论 -->
<form action="addComment" method="post">
<input type="hidden" name="postId" value="123" />
<input type="text" name="author" placeholder="你的名字" required /><br/>
<textarea name="content" placeholder="写点什么..." required></textarea><br/>
<button type="submit">发表评论</button>
</form></p><p><hr/></p><p><!-- 显示评论列表 -->
<% List<Comment> comments = (List<Comment>) request.getAttribute("comments");
for (Comment c : comments) { %>
<div style="margin-left: <%= c.getParentId() == null ? 0 : 20 %>px; border-left: 2px solid #ccc; padding-left: 10px;">
<b><%= c.getAuthor() %></b>: <%= c.getContent() %>
<small><%= c.getCreatedAt() %></small>
<button onclick="replyTo(<%= c.getId() %>)">回复</button>
</div>
<% } %></p><p><script>
function replyTo(parentId) {
document.querySelector("input[name='parentId']").value = parentId;
window.scrollTo(0, 0);
}
</script>
</body>
</html></p>基本上就这些。这个方案适合学习或小型项目。后续可扩展的功能包括:用户登录校验、评论审核、分页加载、防XSS过滤等。
以上就是如何用Java开发小型论坛评论功能的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号