想实现利用servlet和tomcat将mysql中db1数据库中student表中包含id、name、tel的值用JSP显示,你可以给我写出完整的代码吗?
时间: 2023-12-03 17:46:09 浏览: 36
好的,下面是实现利用servlet和tomcat将mysql中db1数据库中student表中包含id、name、tel的值用JSP显示的完整代码:
Student.java
```java
public class Student {
private int id;
private String name;
private String tel;
public Student(int id, String name, String tel) {
this.id = id;
this.name = name;
this.tel = tel;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getTel() {
return tel;
}
}
```
StudentDao.java
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class StudentDao {
private final String URL = "jdbc:mysql://localhost:3306/db1";
private final String USERNAME = "root";
private final String PASSWORD = "password";
public List<Student> getAllStudents() throws SQLException {
List<Student> students = new ArrayList<>();
try (Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
PreparedStatement ps = conn.prepareStatement("SELECT id, name, tel FROM student");
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String tel = rs.getString("tel");
students.add(new Student(id, name, tel));
}
}
return students;
}
}
```
StudentServlet.java
```java
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class StudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
StudentDao studentDao = new StudentDao();
List<Student> students = studentDao.getAllStudents();
request.setAttribute("students", students);
request.getRequestDispatcher("students.jsp").forward(request, response);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
students.jsp
```html
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>学生列表</title>
</head>
<body>
<h1>学生列表</h1>
<table border="1">
<tr>
<th>ID</th>
<th>姓名</th>
<th>电话</th>
</tr>
<c:forEach items="${students}" var="student">
<tr>
<td>${student.id}</td>
<td>${student.name}</td>
<td>${student.tel}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
```
需要注意的是,为了能够使用 JSP 标签库,需要在 JSP 页面的开头添加以下声明:
```html
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
```
此外,还需要把 MySQL 驱动程序的 jar 包放到 WEB-INF/lib 目录下。