使用servlet展示数据库表单
时间: 2024-06-11 13:10:57 浏览: 86
以下是一个简单的示例,展示如何使用servlet从数据库中检索数据并将其显示为表格形式。
1. 首先,需要创建一个数据库表格,例如“students”,包含以下字段:id,name,age,gender。
2. 然后,创建一个servlet,命名为“DisplayStudentsServlet”,用于检索数据库中的所有学生信息并将其显示为HTML表格。
```
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DisplayStudentsServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置响应内容类型
response.setContentType("text/html;charset=UTF-8");
// 获取输出流
PrintWriter out = response.getWriter();
String title = "学生信息表格";
String docType = "<!DOCTYPE html>";
out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n"
+ "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n");
try {
// 加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 连接数据库
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC", "root", "password");
// 执行查询
Statement stmt = conn.createStatement();
String sql = "SELECT id, name, age, gender FROM students";
ResultSet rs = stmt.executeQuery(sql);
// 创建表格
out.println("<table border=\"1\" align=\"center\">\n" + "<tr bgcolor=\"#ffad00\">\n"
+ "<th>ID</th><th>姓名</th><th>年龄</th><th>性别</th>\n" + "</tr>\n");
// 填充表格
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String gender = rs.getString("gender");
out.println("<tr>\n" + "<td>" + id + "</td>\n" + "<td>" + name + "</td>\n" + "<td>" + age
+ "</td>\n" + "<td>" + gender + "</td>\n" + "</tr>\n");
}
out.println("</table>\n");
// 关闭连接
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
out.println("</body></html>");
}
}
```
3. 在web.xml文件中添加servlet映射:
```
<servlet>
<servlet-name>DisplayStudentsServlet</servlet-name>
<servlet-class>DisplayStudentsServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DisplayStudentsServlet</servlet-name>
<url-pattern>/displayStudents</url-pattern>
</servlet-mapping>
```
4. 启动Tomcat服务器,并在浏览器中访问以下URL:
```
http://localhost:8080/yourWebAppName/displayStudents
```
这将调用我们的servlet并显示学生信息表格。
阅读全文