javaee编写一个增删改查
时间: 2023-09-14 15:08:37 浏览: 136
java增删改查
好的,以下是一个简单的 JavaEE 实现增删改查(CRUD)的示例:
首先,创建一个名为 `User` 的 JavaBean,表示一个用户,包含以下属性和方法:
```java
public class User {
private int id;
private String name;
private int age;
// 省略构造方法和getter/setter方法
// toString方法,用于输出用户信息
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
```
接下来,创建一个 DAO(数据访问对象) 接口 `UserDao`,定义增删改查的方法:
```java
public interface UserDao {
// 添加用户
public void addUser(User user);
// 根据ID删除用户
public void deleteUser(int id);
// 修改用户信息
public void updateUser(User user);
// 根据ID查询用户信息
public User getUserById(int id);
// 查询所有用户信息
public List<User> getAllUsers();
}
```
然后,创建一个 `UserDaoImpl` 类实现 `UserDao` 接口,使用 JDBC 连接数据库进行数据操作:
```java
public class UserDaoImpl implements UserDao {
// JDBC连接对象
private Connection conn;
// 构造方法,获取JDBC连接
public UserDaoImpl() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 添加用户
public void addUser(User user) {
try {
PreparedStatement ps = conn.prepareStatement("insert into user(name, age) values(?, ?)");
ps.setString(1, user.getName());
ps.setInt(2, user.getAge());
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 根据ID删除用户
public void deleteUser(int id) {
try {
PreparedStatement ps = conn.prepareStatement("delete from user where id = ?");
ps.setInt(1, id);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 修改用户信息
public void updateUser(User user) {
try {
PreparedStatement ps = conn.prepareStatement("update user set name=?, age=? where id=?");
ps.setString(1, user.getName());
ps.setInt(2, user.getAge());
ps.setInt(3, user.getId());
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 根据ID查询用户信息
public User getUserById(int id) {
User user = null;
try {
PreparedStatement ps = conn.prepareStatement("select * from user where id = ?");
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"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
// 查询所有用户信息
public List<User> getAllUsers() {
List<User> userList = new ArrayList<User>();
try {
PreparedStatement ps = conn.prepareStatement("select * from user");
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"));
userList.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
}
return userList;
}
}
```
最后,可以创建一个 `UserServlet` 类作为控制器,处理 HTTP 请求并调用 `UserDao` 对象进行数据操作:
```java
public class UserServlet extends HttpServlet {
private UserDao userDao = new UserDaoImpl(); // 创建UserDao对象
// 处理GET请求,查询所有用户信息
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<User> userList = userDao.getAllUsers();
request.setAttribute("userList", userList);
request.getRequestDispatcher("/userList.jsp").forward(request, response);
}
// 处理POST请求,添加或修改用户信息
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
if ("add".equals(action)) { // 添加用户信息
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
User user = new User();
user.setName(name);
user.setAge(age);
userDao.addUser(user);
response.sendRedirect(request.getContextPath() + "/user");
} else if ("update".equals(action)) { // 修改用户信息
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
User user = new User();
user.setId(id);
user.setName(name);
user.setAge(age);
userDao.updateUser(user);
response.sendRedirect(request.getContextPath() + "/user");
}
}
// 处理DELETE请求,删除用户信息
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
userDao.deleteUser(id);
response.getWriter().write("success");
}
}
```
最后,可以创建一个 `userList.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 border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<c:forEach items="${userList}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.age}</td>
<td><a href="<c:url value='/user/edit'/>?id=${user.id}">Edit</a></td>
<td><a href="javascript:void(0)" onclick="deleteUser(${user.id}, this)">Delete</a></td>
</tr>
</c:forEach>
</table>
<h2>Add User</h2>
<form action="<c:url value='/user'/>" method="post">
<input type="hidden" name="action" value="add"/>
Name: <input type="text" name="name"/><br/>
Age: <input type="text" name="age"/><br/>
<input type="submit" value="Submit"/>
</form>
<h2>Edit User</h2>
<form action="<c:url value='/user'/>" method="post">
<input type="hidden" name="action" value="update"/>
<input type="hidden" name="id" value="${param.id}"/>
Name: <input type="text" name="name" value="${user.name}"/><br/>
Age: <input type="text" name="age" value="${user.age}"/><br/>
<input type="submit" value="Submit"/>
</form>
<script>
// 删除用户信息
function deleteUser(id, link) {
if (confirm("Are you sure to delete this user?")) {
var xhr = new XMLHttpRequest();
xhr.open("DELETE", "<c:url value='/user'/>?id=" + id, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert("Delete user successfully.");
link.parentNode.parentNode.remove();
}
};
xhr.send();
}
}
</script>
</body>
</html>
```
以上就是一个简单的 JavaEE 实现增删改查的示例,可以根据实际需求进行修改和完善。
阅读全文