JSP(JavaServer Pages)是一种用于创建动态Web内容的技术,它允许在HTML页面中嵌入Java代码。实现评论功能通常涉及前端页面的设计、后端逻辑的处理以及数据库的交互。以下是一个简单的JSP实现评论功能的示例:
CREATE TABLE comments (
id INT AUTO_INCREMENT PRIMARY KEY,
content TEXT NOT NULL,
user_id INT NOT NULL,
post_id INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
<%@ page import="java.sql.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>评论系统</title>
</head>
<body>
<h1>发表评论</h1>
<form action="submit_comment.jsp" method="post">
内容: <textarea name="content"></textarea><br>
用户ID: <input type="text" name="user_id"><br>
文章ID: <input type="text" name="post_id"><br>
<input type="submit" value="提交">
</form>
<h1>所有评论</h1>
<%
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/yourdb", "username", "password");
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM comments ORDER BY created_at DESC");
while (rs.next()) {
out.println("<p>" + rs.getString("content") + " - " + rs.getTimestamp("created_at") + "</p>");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
}
%>
</body>
</html>
<%@ page import="java.sql.*" %>
<%
String content = request.getParameter("content");
int userId = Integer.parseInt(request.getParameter("user_id"));
int postId = Integer.parseInt(request.getParameter("post_id"));
Connection conn = null;
PreparedStatement pstmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/yourdb", "username", "password");
String sql = "INSERT INTO comments (content, user_id, post_id) VALUES (?, ?, ?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, content);
pstmt.setInt(2, userId);
pstmt.setInt(3, postId);
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
}
response.sendRedirect("comment.jsp");
%>
PreparedStatement
而不是Statement
来防止SQL注入。通过以上步骤,你可以实现一个基本的JSP评论功能。根据实际需求,可以进一步扩展和优化。
领取专属 10元无门槛券
手把手带您无忧上云