Servlet分页删除代码
时间: 2024-02-26 19:58:46 浏览: 54
Servlet实现分页效果
以下是使用Servlet实现分页删除的示例代码,该代码使用MySQL数据库和JSP页面:
JSP页面(list.jsp):
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户列表</title>
</head>
<body>
<h1>用户列表</h1>
<table>
<tr>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.age}</td>
<td>
<form method="post" action="delete">
<input type="hidden" name="id" value="${user.id}">
<input type="submit" value="删除">
</form>
</td>
</tr>
</c:forEach>
</table>
<div>
<c:if test="${page > 1}">
<a href="?page=${page - 1}"><上一页</a>
</c:if>
<c:if test="${page < totalPage}">
<a href="?page=${page + 1}">下一页></a>
</c:if>
</div>
</body>
</html>
```
Servlet代码(ListServlet.java):
```java
import java.io.IOException;
import java.util.List;
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("/list")
public class ListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserDao userDao = new UserDaoImpl();
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int page;
try {
page = Integer.parseInt(request.getParameter("page"));
} catch (NumberFormatException e) {
page = 1;
}
int pageSize = 10;
int offset = (page - 1) * pageSize;
int totalRecords = userDao.countAll();
int totalPage = (int) Math.ceil((double) totalRecords / pageSize);
List<User> users = userDao.findAll(offset, pageSize);
request.setAttribute("users", users);
request.setAttribute("page", page);
request.setAttribute("totalPage", totalPage);
request.getRequestDispatcher("list.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
userDao.delete(id);
response.sendRedirect("list");
}
}
```
在上述代码中,我们首先获取当前页码并计算偏移量和总记录数。然后,我们查询当前页的记录并将它们存储在请求属性中。接下来,我们将页码和总页数也存储在请求属性中,并将请求转发到JSP页面进行显示。最后,我们处理删除操作,并将用户重定向到用户列表页面。
阅读全文