用Java和mysql做一个简单的学生管理系统并且可以用页面操作
时间: 2024-03-07 11:49:50 浏览: 31
确实可以使用Java和MySQL来实现一个简单的学生管理系统,并且可以通过页面进行操作。这里给出一个简单的示例,该示例使用Java Servlet和JSP技术来实现网页界面,并使用MySQL存储数据。以下是实现步骤:
1. 创建一个名为`Student`的Java类,该类表示学生对象,包括学生ID、姓名和年龄等属性,以及对这些属性的读写方法。
```java
public class Student {
private int id;
private String name;
private int age;
public Student() {
}
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = 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;
}
}
```
2. 创建一个名为`StudentDAO`的Java类,该类表示数据访问对象,负责管理学生对象的持久化存储。该类包括以下方法:
- `getConnection()`:获取数据库连接。
- `closeConnection(Connection conn)`:关闭数据库连接。
- `add(Student student)`:添加一个学生对象到数据库中。
- `delete(int id)`:从数据库中删除一个学生对象。
- `update(Student student)`:更新一个学生对象在数据库中的信息。
- `get(int id)`:从数据库中查找一个学生对象。
- `getAll()`:从数据库中获取所有的学生对象列表。
```java
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class StudentDAO {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/test";
private static final String USERNAME = "root";
private static final String PASSWORD = "password";
public Connection getConnection() throws SQLException {
Connection conn = null;
try {
Class.forName(DRIVER);
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return conn;
}
public void closeConnection(Connection conn) throws SQLException {
if (conn != null) {
conn.close();
}
}
public void add(Student student) throws SQLException {
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement("INSERT INTO student(name, age) VALUES(?, ?)");
ps.setString(1, student.getName());
ps.setInt(2, student.getAge());
ps.executeUpdate();
ps.close();
closeConnection(conn);
}
public void delete(int id) throws SQLException {
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement("DELETE FROM student WHERE id=?");
ps.setInt(1, id);
ps.executeUpdate();
ps.close();
closeConnection(conn);
}
public void update(Student student) throws SQLException {
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement("UPDATE student SET name=?, age=? WHERE id=?");
ps.setString(1, student.getName());
ps.setInt(2, student.getAge());
ps.setInt(3, student.getId());
ps.executeUpdate();
ps.close();
closeConnection(conn);
}
public Student get(int id) throws SQLException {
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT * FROM student WHERE id=?");
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
Student student = null;
if (rs.next()) {
student = new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
}
rs.close();
ps.close();
closeConnection(conn);
return student;
}
public List<Student> getAll() throws SQLException {
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT * FROM student");
ResultSet rs = ps.executeQuery();
List<Student> students = new ArrayList<>();
while (rs.next()) {
Student student = new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
students.add(student);
}
rs.close();
ps.close();
closeConnection(conn);
return students;
}
}
```
3. 创建一个名为`StudentServlet`的Java Servlet类,该类处理网页请求。该类包括以下方法:
- `doGet(HttpServletRequest request, HttpServletResponse response)`:处理GET请求,显示学生列表或单个学生信息。
- `doPost(HttpServletRequest request, HttpServletResponse response)`:处理POST请求,添加、修改或删除学生信息。
```java
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
public class StudentServlet extends HttpServlet {
private StudentDAO studentDAO = new StudentDAO();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
if (action == null) {
List<Student> students = null;
try {
students = studentDAO.getAll();
} catch (SQLException e) {
e.printStackTrace();
}
request.setAttribute("students", students);
request.getRequestDispatcher("/WEB-INF/views/student/list.jsp").forward(request, response);
} else if (action.equals("add")) {
request.getRequestDispatcher("/WEB-INF/views/student/add.jsp").forward(request, response);
} else if (action.equals("edit")) {
int id = Integer.parseInt(request.getParameter("id"));
Student student = null;
try {
student = studentDAO.get(id);
} catch (SQLException e) {
e.printStackTrace();
}
request.setAttribute("student", student);
request.getRequestDispatcher("/WEB-INF/views/student/edit.jsp").forward(request, response);
} else if (action.equals("delete")) {
int id = Integer.parseInt(request.getParameter("id"));
try {
studentDAO.delete(id);
} catch (SQLException e) {
e.printStackTrace();
}
response.sendRedirect(request.getContextPath() + "/student");
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
if (action.equals("add")) {
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
Student student = new Student();
student.setName(name);
student.setAge(age);
try {
studentDAO.add(student);
} catch (SQLException e) {
e.printStackTrace();
}
response.sendRedirect(request.getContextPath() + "/student");
} else if (action.equals("edit")) {
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
Student student = new Student();
student.setId(id);
student.setName(name);
student.setAge(age);
try {
studentDAO.update(student);
} catch (SQLException e) {
e.printStackTrace();
}
response.sendRedirect(request.getContextPath() + "/student");
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
}
```
4. 创建一个名为`list.jsp`的JSP文件,该文件显示学生列表和操作链接。
```html
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>学生列表</title>
</head>
<body>
<h1>学生列表</h1>
<table border="1">
<tr>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
<c:forEach var="student" items="${students}">
<tr>
<td>${student.id}</td>
<td>${student.name}</td>
<td>${student.age}</td>
<td>
<a href="${pageContext.request.contextPath}/student?action=edit&id=${student.id}">编辑</a>
<a href="${pageContext.request.contextPath}/student?action=delete&id=${student.id}">删除</a>
</td>
</tr>
</c:forEach>
</table>
<br>
<a href="${pageContext.request.contextPath}/student?action=add">添加学生</a>
</body>
</html>
```
5. 创建一个名为`add.jsp`的JSP文件,该文件显示添加学生的表单。
```html
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>添加学生</title>
</head>
<body>
<h1>添加学生</h1>
<form action="${pageContext.request.contextPath}/student" method="post">
<input type="hidden" name="action" value="add">
<table>
<tr>
<td>姓名:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>年龄:</td>
<td><input type="text" name="age"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="添加"></td>
</tr>
</table>
</form>
</body>
</html>
```
6. 创建一个名为`edit.jsp`的JSP文件,该文件显示编辑学生的表单。
```html
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>编辑学生</title>
</head>
<body>
<h1>编辑学生</h1>
<form action="${pageContext.request.contextPath}/student" method="post">
<input type="hidden" name="action" value="edit">
<input type="hidden" name="id" value="${student.id}">
<table>
<tr>
<td>姓名:</td>
<td><input type="text" name="name" value="${student.name}"></td>
</tr>
<tr>
<td>年龄:</td>
<td><input type="text" name="age" value="${student.age}"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="保存"></td>
</tr>
</table>
</form>
</body>
</html>
```
7. 创建一个名为`web.xml`的Web应用程序部署描述文件,该文件指定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>StudentServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>StudentServlet</servlet-name>
<url-pattern>/student</url-pattern>
</servlet-mapping>
</web-app>
```
8. 将以上代码保存到对应的文件中,并将JSP文件放置到`/WEB-INF/views/student/`目录下。然后在本地MySQL数据库中创建一个名为`test`的数据库,运行以下SQL语句以创建学生表:
```sql
CREATE TABLE `student` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(20) NOT NULL,
`age` INT NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
```
9. 最后,启动Tomcat服务器,访问`http://localhost:8080/项目名称/student`即可进入学生列表页面。从该页面可以添加、编辑和删除学生信息。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)