jsp写一个增删改查界面
时间: 2024-05-03 22:16:53 浏览: 102
这里提供一个基于 JSP 和 Servlet 的增删改查(CRUD)示例。
先建立一个数据库表,例如名为 `student`,包含字段 `id`、`name` 和 `age`。
在 `WEB-INF` 目录下新建 `lib` 目录,并将 MySQL 驱动程序(`mysql-connector-java-x.x.xx.jar`)放入其中。
在 `WEB-INF` 目录下新建 `classes` 目录,在其中创建一个名为 `StudentBean` 的 JavaBean 类,用于封装学生信息:
```java
public class StudentBean {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
```
在 `WEB-INF` 目录下新建 `web.xml` 文件,配置 Servlet 和 JSP:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>StudentServlet</servlet-name>
<servlet-class>com.example.StudentServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>StudentServlet</servlet-name>
<url-pattern>/student/*</url-pattern>
</servlet-mapping>
</web-app>
```
在 `WEB-INF` 目录下新建 `student.jsp` 文件,用于展示学生列表和表单:
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.List" %>
<%@ page import="com.example.StudentBean" %>
<%@ page import="com.example.StudentDAO" %>
<!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>
<th>操作</th>
</tr>
<% List<StudentBean> students = StudentDAO.getAllStudents();
for (StudentBean student : students) { %>
<tr>
<td><%= student.getId() %></td>
<td><%= student.getName() %></td>
<td><%= student.getAge() %></td>
<td>
<form method="post" action="student">
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="id" value="<%= student.getId() %>">
<input type="submit" value="删除">
</form>
<form method="get" action="student/<%= student.getId() %>">
<input type="submit" value="编辑">
</form>
</td>
</tr>
<% } %>
</table>
<h2>添加学生</h2>
<form method="post" action="student">
<input type="hidden" name="_method" value="POST">
姓名:<input type="text" name="name"><br>
年龄:<input type="text" name="age"><br>
<input type="submit" value="添加">
</form>
</body>
</html>
```
其中,使用 `<% %>` 包裹的代码块中,通过 `StudentDAO` 类获取所有学生信息,并展示在表格中。每一行中,通过两个表单按钮分别进行删除和编辑操作。
在 `src` 目录下新建 `StudentDAO` 类,用于访问数据库:
```java
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class StudentDAO {
private static final String URL = "jdbc:mysql://localhost:3306/test";
private static final String USER = "root";
private static final String PASSWORD = "password";
public static List<StudentBean> getAllStudents() {
List<StudentBean> students = new ArrayList<>();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
while (rs.next()) {
StudentBean student = new StudentBean();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
students.add(student);
}
rs.close();
stmt.close();
conn.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return students;
}
public static void addStudent(StudentBean student) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO student (name, age) VALUES (?, ?)");
pstmt.setString(1, student.getName());
pstmt.setInt(2, student.getAge());
pstmt.executeUpdate();
pstmt.close();
conn.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
public static void deleteStudent(int id) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
PreparedStatement pstmt = conn.prepareStatement("DELETE FROM student WHERE id = ?");
pstmt.setInt(1, id);
pstmt.executeUpdate();
pstmt.close();
conn.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
public static StudentBean getStudent(int id) {
StudentBean student = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM student WHERE id = ?");
pstmt.setInt(1, id);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
student = new StudentBean();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
}
rs.close();
pstmt.close();
conn.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return student;
}
public static void updateStudent(StudentBean student) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
PreparedStatement pstmt = conn.prepareStatement("UPDATE student SET name = ?, age = ? WHERE id = ?");
pstmt.setString(1, student.getName());
pstmt.setInt(2, student.getAge());
pstmt.setInt(3, student.getId());
pstmt.executeUpdate();
pstmt.close();
conn.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}
```
其中,`getAllStudents` 方法用于获取所有学生信息,`addStudent` 方法用于添加学生,`deleteStudent` 方法用于删除学生,`getStudent` 方法用于获取指定 ID 的学生信息,`updateStudent` 方法用于更新学生信息。
在 `src` 目录下新建 `StudentServlet` 类,用于处理 HTTP 请求:
```java
import java.io.IOException;
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("/student/*")
public class StudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String pathInfo = request.getPathInfo();
if (pathInfo == null || pathInfo.equals("/")) {
request.getRequestDispatcher("/WEB-INF/student.jsp").forward(request, response);
} else {
int id = Integer.parseInt(pathInfo.substring(1));
StudentBean student = StudentDAO.getStudent(id);
if (student == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} else {
request.setAttribute("student", student);
request.getRequestDispatcher("/WEB-INF/student_edit.jsp").forward(request, response);
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String method = request.getParameter("_method");
if (method == null) {
StudentBean student = new StudentBean();
student.setName(request.getParameter("name"));
student.setAge(Integer.parseInt(request.getParameter("age")));
StudentDAO.addStudent(student);
} else if (method.equals("DELETE")) {
int id = Integer.parseInt(request.getParameter("id"));
StudentDAO.deleteStudent(id);
} else if (method.equals("PUT")) {
StudentBean student = new StudentBean();
student.setId(Integer.parseInt(request.getParameter("id")));
student.setName(request.getParameter("name"));
student.setAge(Integer.parseInt(request.getParameter("age")));
StudentDAO.updateStudent(student);
}
response.sendRedirect(request.getContextPath() + "/student");
}
protected void doPut(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String pathInfo = request.getPathInfo();
if (pathInfo == null || pathInfo.equals("/")) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
} else {
int id = Integer.parseInt(pathInfo.substring(1));
StudentBean student = StudentDAO.getStudent(id);
if (student == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} else {
request.setAttribute("student", student);
request.getRequestDispatcher("/WEB-INF/student_edit.jsp").forward(request, response);
}
}
}
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String pathInfo = request.getPathInfo();
if (pathInfo == null || pathInfo.equals("/")) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
} else {
int id = Integer.parseInt(pathInfo.substring(1));
StudentDAO.deleteStudent(id);
response.sendRedirect(request.getContextPath() + "/student");
}
}
}
```
其中,`doGet` 方法用于处理 GET 请求,根据 URL 中的 ID 参数,展示所有学生或编辑指定学生信息。`doPost` 方法用于处理 POST 请求,根据 `_method` 参数,添加、删除或更新学生信息。`doPut` 和 `doDelete` 方法分别用于处理 PUT 和 DELETE 请求,用于更新和删除学生信息。
在 `WEB-INF` 目录下新建 `student_edit.jsp` 文件,用于编辑学生信息:
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="com.example.StudentBean" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>编辑学生信息</title>
</head>
<body>
<h1>编辑学生信息</h1>
<form method="post" action="student">
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="id" value="<%= request.getAttribute("student").getId() %>">
姓名:<input type="text" name="name" value="<%= request.getAttribute("student").getName() %>"><br>
年龄:<input type="text" name="age" value="<%= request.getAttribute("student").getAge() %>"><br>
<input type="submit" value="保存">
</form>
</body>
</html>
```
其中,使用 `request.getAttribute` 方法获取传递的学生信息,并在表单中展示。
最后,在浏览器中访问 `http://localhost:8080/项目名/student`,即可访问学生信息管理界面。
阅读全文