JSP(JavaServer Pages)是一种基于Java技术的动态网页开发技术,它允许开发者在HTML或XML等静态页面中嵌入Java代码,从而实现动态内容的生成和交互。下面我将详细介绍JSP留言及回复系统的基础概念、优势、类型、应用场景,以及可能遇到的问题和解决方法。
以下是一个简单的JSP留言及回复系统的示例代码:
CREATE TABLE messages (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50),
content TEXT,
reply_to INT DEFAULT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>留言板</title>
</head>
<body>
<h1>留言板</h1>
<form action="submit_message.jsp" method="post">
用户名: <input type="text" name="username"><br>
内容: <textarea name="content"></textarea><br>
回复ID(留空表示新留言): <input type="text" name="reply_to"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
<%@ page import="java.sql.*" %>
<%
String username = request.getParameter("username");
String content = request.getParameter("content");
String replyToStr = request.getParameter("reply_to");
int replyTo = replyToStr.isEmpty() ? null : Integer.parseInt(replyToStr);
Connection conn = null;
PreparedStatement pstmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
String sql = "INSERT INTO messages (username, content, reply_to) VALUES (?, ?, ?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, content);
pstmt.setObject(3, replyTo);
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
}
response.sendRedirect("index.jsp");
%>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>
<html>
<head>
<title>留言列表</title>
</head>
<body>
<h1>留言列表</h1>
<ul>
<%
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM messages ORDER BY created_at DESC");
while (rs.next()) {
int id = rs.getInt("id");
String username = rs.getString("username");
String content = rs.getString("content");
Timestamp createdAt = rs.getTimestamp("created_at");
Integer replyTo = rs.getInt("reply_to");
%>
<li>
<strong><%= username %></strong> <%= createdAt %><br>
<%= content %>
<% if (replyTo != null) { %>
<blockquote>回复于 #<%= replyTo %></blockquote>
<% } %>
<form action="submit_reply.jsp" method="post">
<input type="hidden" name="reply_to" value="<%= id %>">
用户名: <input type="text" name="username"><br>
内容: <textarea name="content"></textarea><br>
<input type="submit" value="回复">
</form>
</li>
<%
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
}
%>
</ul>
</body>
</html>
通过以上内容,你应该能够全面了解JSP留言及回复系统的相关知识,并能够根据实际情况进行开发和维护。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云