1、 创建分页类
public class PageBean<T> { private int pageNum; private int pageSize; private int totalRecord; private int totalPage; private List<T> list; private int start; private int end; private int fromIndex; private int toIndex; public PageBean(int pageNum, int pageSize, int totalRecord) { this.pageNum = pageNum; this.pageSize = pageSize; this.totalRecord = totalRecord; fromIndex=(pageNum-1)*pageSize; toIndex=pageNum*pageSize>totalRecord?totalRecord:pageNum*pageSize; if (totalRecord % pageSize == 0) { this.totalPage = totalRecord / pageSize; } else { this.totalPage = totalRecord / pageSize + 1; } start = 1; end = 5; if (totalPage <= 5) { end = this.totalPage; } else { start = pageNum - 2; end = pageNum + 2; if (start < 1) { start = 1; end = 5; } if (end > this.totalPage) { end = totalPage; start = end - 5; } } } public int getPageNum() { return pageNum; } public void setPageNum(int pageNum) { this.pageNum = pageNum; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getTotalRecord() { return totalRecord; } public int getFromIndex() { return fromIndex; } public void setFromIndex(int fromIndex) { this.fromIndex = fromIndex; } public int getToIndex() { return toIndex; } public void setToIndex(int toIndex) { this.toIndex = toIndex; } public void setTotalRecord(int totalRecord) { this.totalRecord = totalRecord; } public int getTotalPage() { return totalPage; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public List<T> getList() { return list; } public void setList(List<T> list) { this.list = list.subList(fromIndex, toIndex); } public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getEnd() { return end; } public void setEnd(int end) { this.end = end; } }
2、 service层
@WebServlet("/main") public class Servlets extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String page = request.getParameter("pageNum"); int pageNum = Integer.parseInt((page == null ? "1" : page)); int pageSize = 5; Service s = new Service(); PageBean<User> pb = s.findAll(pageNum, pageSize); request.setAttribute("pageBean", pb); request.getRequestDispatcher("/main.jsp").forward(request, response); } }
3、 dao层
public class Service { public PageBean<User> findAll(int pageNum, int pageSize) { UserDao userDao = new UserDao(); List<User> users = userDao.findAll(); int totalRecord = users.size(); PageBean<User> pb = new PageBean<>(pageNum, pageSize, totalRecord); pb.setList(users); return pb; } }