jsp中编写一个查询记录表格
时间: 2024-02-06 10:12:42 浏览: 116
jsp表单
您可以使用JSP和Java Servlet来编写一个查询记录表格。以下是一个简单的示例代码:
1. 在JSP页面中编写查询表单,如下所示:
```
<!DOCTYPE html>
<html>
<head>
<title>Search Records</title>
</head>
<body>
<h1>Search Records</h1>
<form method="post" action="SearchServlet">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<input type="submit" value="Search">
</form>
</body>
</html>
```
2. 创建一个Java Servlet来处理查询请求和响应,如下所示:
```
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/SearchServlet")
public class SearchServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
String sql = "SELECT * FROM records WHERE name LIKE '%" + name + "%'";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Search Results</title></head><body>");
out.println("<h1>Search Results</h1>");
out.println("<table border='1'><tr><th>Name</th><th>Email</th><th>Phone</th></tr>");
while (rs.next()) {
String recordName = rs.getString("name");
String email = rs.getString("email");
String phone = rs.getString("phone");
out.println("<tr><td>" + recordName + "</td><td>" + email + "</td><td>" + phone + "</td></tr>");
}
out.println("</table></body></html>");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
在这个示例中,我们使用了MySQL数据库来存储记录信息。您需要根据实际情况更改数据库连接信息。在Servlet中,我们使用JDBC API来执行SQL查询,并将结果呈现为HTML表格。请注意,这只是一个示例代码,您需要根据实际需求进行修改和优化。
阅读全文