jsp+servlet实现增删改查功能
时间: 2023-12-26 14:03:40 浏览: 102
要实现增删改查功能,一般使用MVC模式来开发,其中Model层用于操作数据,View层用于展示数据,Controller层用于处理用户请求并调用Model层和View层。
下面是一个简单的示例代码,演示如何使用JSP和Servlet来实现增删改查功能:
1. 建立一个包含数据库连接、增删改查操作的Java类,例如DbUtil.java。
```java
public class DbUtil {
private Connection conn = null;
private PreparedStatement pstmt = null;
private ResultSet rs = null;
// 连接数据库
public void getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8";
String user = "root";
String password = "123456";
conn = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
}
// 关闭数据库连接
public void closeConnection() {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 查询所有用户
public List<User> queryAllUsers() {
List<User> userList = new ArrayList<User>();
try {
getConnection();
String sql = "select * from user";
pstmt = conn.prepareStatement(sql);
rs = pstmt.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 (Exception e) {
e.printStackTrace();
} finally {
closeConnection();
}
return userList;
}
// 根据id查询用户
public User queryUserById(int id) {
User user = null;
try {
getConnection();
String sql = "select * from user where id = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
rs = pstmt.executeQuery();
if (rs.next()) {
user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setAge(rs.getInt("age"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection();
}
return user;
}
// 添加用户
public void addUser(User user) {
try {
getConnection();
String sql = "insert into user(name, age) values (?, ?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, user.getName());
pstmt.setInt(2, user.getAge());
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection();
}
}
// 修改用户
public void updateUser(User user) {
try {
getConnection();
String sql = "update user set name = ?, age = ? where id = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, user.getName());
pstmt.setInt(2, user.getAge());
pstmt.setInt(3, user.getId());
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection();
}
}
// 删除用户
public void deleteUser(int id) {
try {
getConnection();
String sql = "delete from user where id = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection();
}
}
}
```
2. 在Web应用目录下建立一个JSP页面,例如user.jsp,用于展示用户数据。
```jsp
<%@ 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>
<p><a href="add.jsp">添加用户</a></p>
<table border="1">
<tr>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
<%
DbUtil dbUtil = new DbUtil();
List<User> userList = dbUtil.queryAllUsers();
for (User user : userList) {
%>
<tr>
<td><%= user.getId() %></td>
<td><%= user.getName() %></td>
<td><%= user.getAge() %></td>
<td>
<a href="edit.jsp?id=<%= user.getId() %>">编辑</a>
<a href="delete.jsp?id=<%= user.getId() %>"
onclick="return confirm('确定删除该用户吗?')">删除</a>
</td>
</tr>
<%
}
%>
</table>
</body>
</html>
```
3. 在Web应用目录下建立一个Servlet类,例如UserServlet.java,用于处理用户请求。
```java
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if ("add".equals(action)) {
addUser(request, response);
} else if ("edit".equals(action)) {
editUser(request, response);
} else if ("update".equals(action)) {
updateUser(request, response);
} else if ("delete".equals(action)) {
deleteUser(request, response);
} else {
showUserList(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
// 显示用户列表
private void showUserList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("user.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"));
User user = new User();
user.setName(name);
user.setAge(age);
DbUtil dbUtil = new DbUtil();
dbUtil.addUser(user);
response.sendRedirect("UserServlet");
}
// 编辑用户
private void editUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
DbUtil dbUtil = new DbUtil();
User user = dbUtil.queryUserById(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"));
User user = new User();
user.setId(id);
user.setName(name);
user.setAge(age);
DbUtil dbUtil = new DbUtil();
dbUtil.updateUser(user);
response.sendRedirect("UserServlet");
}
// 删除用户
private void deleteUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
DbUtil dbUtil = new DbUtil();
dbUtil.deleteUser(id);
response.sendRedirect("UserServlet");
}
}
```
4. 在Web应用目录下建立一个JSP页面,例如add.jsp,用于添加用户。
```jsp
<%@ 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>
<form action="UserServlet?action=add" method="post">
<table>
<tr>
<td>姓名:</td>
<td><input type="text" name="name" required></td>
</tr>
<tr>
<td>年龄:</td>
<td><input type="number" name="age" required></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="添加"></td>
</tr>
</table>
</form>
</body>
</html>
```
5. 在Web应用目录下建立一个JSP页面,例如edit.jsp,用于编辑用户。
```jsp
<%@ 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>
<form action="UserServlet?action=update" method="post">
<input type="hidden" name="id" value="<%= request.getAttribute("user").getId() %>">
<table>
<tr>
<td>姓名:</td>
<td><input type="text" name="name" value="<%= request.getAttribute("user").getName() %>" required></td>
</tr>
<tr>
<td>年龄:</td>
<td><input type="number" name="age" value="<%= request.getAttribute("user").getAge() %>" required></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="保存"></td>
</tr>
</table>
</form>
</body>
</html>
```
6. 在Web应用目录下建立一个JSP页面,例如delete.jsp,用于删除用户。
```jsp
<%@ 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>
<form action="UserServlet?action=delete" method="post">
<input type="hidden" name="id" value="<%= request.getParameter("id") %>">
<p>确定删除该用户吗?</p>
<p><input type="submit" value="确定"></p>
</form>
</body>
</html>
```
7. 在Web应用目录下建立一个Java类,例如User.java,用于封装用户数据。
```java
public class User {
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;
}
}
```
以上就是一个简单的JSP和Servlet实现增删改查功能的示例代码,可以根据自己的需求进行修改和优化。
阅读全文