首先搭建数据库并设计评论表,然后创建实体类、DAO数据访问层和Servlet处理评论的增查请求,最后通过JSP页面实现前端展示与提交功能,完成一个基于Java Web的基础评论系统。

要开发一个简易的论坛评论功能,核心是实现用户发表评论、查看评论列表的基本交互。使用Java结合Servlet和JSP(或Thymeleaf等模板引擎)以及数据库(如MySQL),可以快速搭建一个基础版本。以下是关键步骤和代码示例。
CREATE TABLE comment (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
content TEXT NOT NULL,
create_time DATETIME DEFAULT CURRENT_TIMESTAMP
);
public class Comment {
private int id;
private String username;
private String content;
private java.util.Date createTime;
<pre class='brush:java;toolbar:false;'>// 构造方法
public Comment() {}
public Comment(String username, String content) {
this.username = username;
this.content = content;
}
// Getter 和 Setter 方法
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getContent() { return content; }
public void setContent(String content) { this.content = content; }
public java.util.Date getCreateTime() { return createTime; }
public void setCreateTime(java.util.Date createTime) { this.createTime = createTime; }}
立即学习“Java免费学习笔记(深入)”;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
<p>public class CommentDao {
private String jdbcURL = "jdbc:mysql://localhost:3306/forum_db";
private String jdbcUsername = "root";
private String jdbcPassword = "your_password";
private Connection getConnection() throws SQLException {
return DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword);
}</p><pre class='brush:java;toolbar:false;'>// 获取所有评论
public List<Comment> getAllComments() {
List<Comment> comments = new ArrayList<>();
String sql = "SELECT * FROM comment ORDER BY create_time DESC";
try (Connection conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
Comment comment = new Comment();
comment.setId(rs.getInt("id"));
comment.setUsername(rs.getString("username"));
comment.setContent(rs.getString("content"));
comment.setCreateTime(new java.util.Date(rs.getTimestamp("create_time").getTime()));
comments.add(comment);
}
} catch (SQLException e) {
e.printStackTrace();
}
return comments;
}
// 添加新评论
public void addComment(Comment comment) {
String sql = "INSERT INTO comment (username, content) VALUES (?, ?)";
try (Connection conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, comment.getUsername());
stmt.setString(2, comment.getContent());
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}}
立即学习“Java免费学习笔记(深入)”;
@WebServlet("/comment")
public class CommentServlet extends HttpServlet {
private CommentDao commentDao = new CommentDao();
<pre class='brush:java;toolbar:false;'>@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<Comment> comments = commentDao.getAllComments();
request.setAttribute("comments", comments);
request.getRequestDispatcher("/comment.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
String content = request.getParameter("content");
if (username != null && content != null && !username.trim().isEmpty() && !content.trim().isEmpty()) {
Comment comment = new Comment(username, content);
commentDao.addComment(comment);
}
response.sendRedirect("comment");
}}
立即学习“Java免费学习笔记(深入)”;
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>简易论坛评论</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.comment { border-bottom: 1px solid #ccc; padding: 10px 0; }
form { margin-top: 20px; }
</style>
</head>
<body>
<h2>发表评论</h2>
<form method="post">
<label>用户名:<input type="text" name="username" required /></label><br><br>
<label>评论内容:</label><br>
<textarea name="content" rows="4" cols="50" required></textarea><br><br>
<button type="submit">提交评论</button>
</form>
<pre class='brush:java;toolbar:false;'><h2>所有评论</h2>
<c:forEach var="comment" items="${comments}">
<div class="comment">
<strong>${comment.username}</strong>
<small> (${comment.createTime})</small><br>
${comment.content}
</div>
</c:forEach></body> </html>
访问 https://www.php.cn/link/f512bcc142683f9185ea27c41855ed64 即可看到评论页面。
基本上就这些。这个简易系统没有用户登录、防注入、分页等功能,适合学习Servlet+JSP+数据库的基础流程。后续可扩展为Spring Boot项目提升开发效率。
以上就是在Java中如何开发简易论坛评论功能的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号