JSP(Java Server Pages)是一种动态网页技术,它允许在HTML或XML文档中直接嵌入Java代码片段和表达式,这些代码在服务器上执行后生成动态内容。MySQL是一种流行的关系型数据库管理系统,用于存储和管理数据。
以下是一个简单的JSP和MySQL结合的留言板示例:
CREATE TABLE messages (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
message TEXT,
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_message.jsp" method="post">
姓名: <input type="text" name="name"><br>
留言: <textarea name="message"></textarea><br>
<input type="submit" value="提交">
</form>
<h2>留言列表</h2>
<%
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database", "username", "password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM messages ORDER BY created_at DESC");
while (rs.next()) {
%>
<p><strong><%= rs.getString("name") %></strong> - <%= rs.getString("created_at") %></p>
<p><%= rs.getString("message") %></p>
<%
}
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</body>
</html>
<%@ page import="java.sql.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>提交留言</title>
</head>
<body>
<%
String name = request.getParameter("name");
String message = request.getParameter("message");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database", "username", "password");
String sql = "INSERT INTO messages (name, message) VALUES (?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setString(2, message);
pstmt.executeUpdate();
pstmt.close();
conn.close();
response.sendRedirect("index.jsp");
} catch (Exception e) {
e.printStackTrace();
}
%>
</body>
</html>
PreparedStatement
代替Statement
,避免直接拼接SQL语句。希望这些信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云