17370845950

在Java中如何开发简易博客评论系统
答案:通过Servlet、JSP和MySQL实现博客评论系统,包含数据库设计、实体类、DAO层、两个Servlet处理展示与提交、JSP页面显示及表单输入,完成评论的增删查功能。

开发一个简易博客评论系统在Java中可以通过结合Servlet、JSP和数据库来实现。整个系统不需要复杂框架,适合初学者理解Web应用的基本流程。核心功能包括显示评论、提交评论和数据持久化。

1. 设计数据库表结构

使用MySQL存储评论数据,创建一张简单的评论表:

CREATE TABLE comment (
    id INT AUTO_INCREMENT PRIMARY KEY,
    author VARCHAR(50) NOT NULL,
    content TEXT NOT NULL,
    create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

该表包含评论ID、作者名、评论内容和发布时间。

2. 创建Java实体类

定义Comment类映射数据库记录:

public class Comment {
    private int id;
    private String author;
    private String content;
    private Timestamp createTime;
// 构造方法、getter和setter省略

}

3. 实现数据访问层(DAO)

编写CommentDao类用于数据库操作:

public class CommentDao {
    private String jdbcURL = "jdbc:mysql://localhost:3306/blog";
    private String jdbcUsername = "root";
    private String jdbcPassword = "password";
    private Connection getConnection() { /* 获取连接 */ }
public ListzuojiankuohaophpcnCommentyoujiankuohaophpcn getAllComments() {
    ListzuojiankuohaophpcnCommentyoujiankuohaophpcn comments = new ArrayListzuojiankuohaophpcnyoujiankuohaophpcn();
    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 c = new Comment();
            c.setId(rs.getInt("id"));
            c.setAuthor(rs.getString("author"));
            c.setContent(rs.getString("content"));
            c.setCreateTime(rs.getTimestamp("create_time"));
            comments.add(c);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return comments;
}

public void addComment(Comment comment) {
    String sql = "INSERT INTO comment (author, content) VALUES (?, ?)";
    try (Connection conn = getConnection();
         PreparedStatement stmt = conn.prepareStatement(sql)) {
        stmt.setString(1, comment.getAuthor());
        stmt.setString(2, comment.getContent());
        stmt.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

}

4. 使用Servlet处理请求

创建两个Servlet:一个用于显示评论页面,另一个处理提交评论。

ShowCommentServlet 从数据库读取所有评论并转发到JSP页面:

@WebServlet("/show")
public class ShowCommentServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        CommentDao dao = new CommentDao();
        List comments = dao.getAllComments();
        request.setAttribute("comments", comments);
        request.getRequestDispatcher("comment.jsp").forward(request, response);
    }
}

AddCommentServlet 接收表单数据并保存:

@WebServlet("/add")
public class AddCommentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String author = request.getParameter("author");
        String content = request.getParameter("content");
    Comment comment = new Comment();
    comment.setAuthor(author);
    comment.setContent(content);

    CommentDao dao = new CommentDao();
    dao.addComment(comment);

    response.sendRedirect("show");
}

}

5. 编写前端页面(JSP)

创建comment.jsp展示评论列表和输入表单:

发表评论

作者:
内容:

所有评论

<% List comments = (List) request.getAttribute("comments"); if (comments != null) { for (Comment c : comments) { %> <%= c.getAuthor() %> (<%= c.getCreateTime() %>)

<%= c.getContent() %>

<% } } %>

部署项目到Tomcat,确保WEB-INF下有lib目录包含mysql-connector-java和servlet-api.jar。

基本上就这些。这个简易系统展示了Java Web开发的几个关键点:数据库交互、Servlet控制流程、JSP动态输出。后续可扩展验证码、字段校验或分页功能。不复杂但容易忽略编码和SQL安全问题,建议后期引入PreparedStatement防注入,统一设置字符集避免乱码。