利用servlet+jsp+javabean设计一个系统实现增删改查
时间: 2024-02-06 17:02:37 浏览: 69
好的,这是一个比较常见的 Java Web 项目需求,下面我会给出一个简单的实现方式。
1. 前置条件
在开始实现之前,需要确保你已经安装好了 Java 开发环境、Tomcat 服务器和 MySQL 数据库,并且能够使用这些工具进行开发。
2. 创建数据库
首先,需要创建一个数据库和表来存储数据。我们创建一个名为 `user` 的数据库,并在其中创建一个名为 `user_info` 的表,表结构如下:
```sql
CREATE TABLE `user_info` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`gender` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
```
3. 创建 JavaBean
在 `src` 目录下创建一个名为 `User.java` 的 JavaBean,用于表示用户信息:
```java
public class User {
private int id;
private String name;
private int age;
private String gender;
// getter 和 setter 方法
}
```
4. 创建 Dao 类
在 `src` 目录下创建一个名为 `UserDao.java` 的类,用于实现对用户信息的增删改查操作。这里我们使用 JDBC 来访问 MySQL 数据库:
```java
public class UserDao {
private Connection conn;
public UserDao() {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/user";
String username = "root";
String password = "root";
conn = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
}
}
public List<User> getAllUsers() {
List<User> userList = new ArrayList<>();
try {
String sql = "SELECT * FROM user_info";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
User user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setAge(rs.getInt("age"));
user.setGender(rs.getString("gender"));
userList.add(user);
}
} catch (Exception e) {
e.printStackTrace();
}
return userList;
}
public User getUserById(int id) {
User user = null;
try {
String sql = "SELECT * FROM user_info WHERE id=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setAge(rs.getInt("age"));
user.setGender(rs.getString("gender"));
}
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
public void addUser(User user) {
try {
String sql = "INSERT INTO user_info(name, age, gender) VALUES (?, ?, ?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, user.getName());
ps.setInt(2, user.getAge());
ps.setString(3, user.getGender());
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
public void updateUser(User user) {
try {
String sql = "UPDATE user_info SET name=?, age=?, gender=? WHERE id=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, user.getName());
ps.setInt(2, user.getAge());
ps.setString(3, user.getGender());
ps.setInt(4, user.getId());
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
public void deleteUser(int id) {
try {
String sql = "DELETE FROM user_info WHERE id=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, id);
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
5. 创建 Servlet 类
在 `src` 目录下创建一个名为 `UserServlet.java` 的 Servlet 类,用于处理用户请求。这里我们使用 `doGet` 和 `doPost` 方法来处理 GET 和 POST 请求:
```java
public class UserServlet extends HttpServlet {
private UserDao userDao;
public void init() throws ServletException {
userDao = new UserDao();
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if (action == null) {
action = "list";
}
switch (action) {
case "list":
listUsers(request, response);
break;
case "view":
viewUser(request, response);
break;
case "add":
addUser(request, response);
break;
case "edit":
editUser(request, response);
break;
case "delete":
deleteUser(request, response);
break;
default:
listUsers(request, response);
break;
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
private void listUsers(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<User> userList = userDao.getAllUsers();
request.setAttribute("userList", userList);
request.getRequestDispatcher("list.jsp").forward(request, response);
}
private void viewUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
User user = userDao.getUserById(id);
request.setAttribute("user", user);
request.getRequestDispatcher("view.jsp").forward(request, response);
}
private void addUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
String gender = request.getParameter("gender");
User user = new User();
user.setName(name);
user.setAge(age);
user.setGender(gender);
userDao.addUser(user);
response.sendRedirect("UserServlet");
}
private void editUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
User user = userDao.getUserById(id);
request.setAttribute("user", user);
request.getRequestDispatcher("edit.jsp").forward(request, response);
}
private void updateUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
String gender = request.getParameter("gender");
User user = new User();
user.setId(id);
user.setName(name);
user.setAge(age);
user.setGender(gender);
userDao.updateUser(user);
response.sendRedirect("UserServlet");
}
private void deleteUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
userDao.deleteUser(id);
response.sendRedirect("UserServlet");
}
}
```
6. 创建 JSP 页面
在 `WebContent` 目录下创建以下 JSP 页面:
- `list.jsp`:显示用户列表
```html
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>User List</title>
</head>
<body>
<h1>User List</h1>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
<th>Action</th>
</tr>
<c:forEach items="${userList}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.age}</td>
<td>${user.gender}</td>
<td>
<a href="UserServlet?action=view&id=${user.id}">View</a>
<a href="UserServlet?action=edit&id=${user.id}">Edit</a>
<a href="UserServlet?action=delete&id=${user.id}">Delete</a>
</td>
</tr>
</c:forEach>
</table>
<br>
<a href="UserServlet?action=add">Add User</a>
</body>
</html>
```
- `view.jsp`:显示单个用户信息
```html
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>User View</title>
</head>
<body>
<h1>User View</h1>
<table>
<tr>
<td>ID:</td>
<td>${user.id}</td>
</tr>
<tr>
<td>Name:</td>
<td>${user.name}</td>
</tr>
<tr>
<td>Age:</td>
<td>${user.age}</td>
</tr>
<tr>
<td>Gender:</td>
<td>${user.gender}</td>
</tr>
</table>
<br>
<a href="UserServlet">Back to List</a>
</body>
</html>
```
- `add.jsp`:添加用户表单
```html
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Add User</title>
</head>
<body>
<h1>Add User</h1>
<form action="UserServlet" method="post">
<input type="hidden" name="action" value="add">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" name="age"></td>
</tr>
<tr>
<td>Gender:</td>
<td>
<input type="radio" name="gender" value="Male">Male
<input type="radio" name="gender" value="Female">Female
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Add"></td>
</tr>
</table>
</form>
<br>
<a href="UserServlet">Back to List</a>
</body>
</html>
```
- `edit.jsp`:编辑用户表单
```html
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Edit User</title>
</head>
<body>
<h1>Edit User</h1>
<form action="UserServlet" method="post">
<input type="hidden" name="action" value="edit">
<input type="hidden" name="id" value="${user.id}">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name" value="${user.name}"></td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" name="age" value="${user.age}"></td>
</tr>
<tr>
<td>Gender:</td>
<td>
<input type="radio" name="gender" value="Male" ${user.gender=='Male'?'checked':''}>Male
<input type="radio" name="gender" value="Female" ${user.gender=='Female'?'checked':''}>Female
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Save"></td>
</tr>
</table>
</form>
<br>
<a href="UserServlet">Back to List</a>
</body>
</html>
```
7. 部署项目
将编写好的项目打包成 WAR 文件,并将其部署到 Tomcat 服务器中,启动 Tomcat 服务器,在浏览器中访问 `http://localhost:8080/项目名/UserServlet` 即可访问该系统。
至此,一个简单的基于 Servlet+jsp+javabean 的增删改查系统就完成了。
阅读全文