分页在javaweb当中是一个很重要的内容,我们必须要去掌握。
在这里,具体介绍一下分页的代码实现。我们使用mysql数据库,c3p0连接池和最原始的servlet来实现分页操作。(这里没有设计接口,标准开发是需要设计相应接口的)
首先,需要引入jar包,包括mysql的jar包,c3p0的jar包,jtsl jar包,dbutils jar文件,我们用dbutils组件来对数据库进行操作。
首先配置c3p0连接池的xml文件。
<?xml version="1.0" encoding="UTF-8" ?>
<c3p0-config>
<default-config>
<property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/jdbc_demo</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="acquireIncrement">3</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">2</property>
<property name="maxPoolSize">10</property>
</default-config>
</c3p0-config>
然后写一个工具类用于获取数据库的连接
public class JdbcUtils {
private static DataSource dataSource;
static {
dataSource = new ComboPooledDataSource();
}
public static QueryRunner getQueryRunner(){
return new QueryRunner(dataSource);
}
}
配置工作完成,接下来创建pagebean类,用于存放分页需要用到的各种信息,在这里需要使用泛型类,这样任何类型的数据都可以用这个类来进行封装。
package entity;
import java.util.List;
public class PageBean<T> {
private int currentPage = 1; // 当前页 默认第一页
private int pageCount = 4; // 每页显示的行数 默认显示4行
private int totalCount; // 总记录数 totalPage/pageCount 或 totalPage/pageCount+1
private int totalPage; // 总页数
private List<T> pageData; // 分页查询到的数据
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getPageCount() {
return pageCount;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getTotalPage() {
if(totalCount % pageCount == 0){
totalPage = totalCount / pageCount;
}else{
totalPage = totalCount / pageCount + 1;
}
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public List<T> getPageData() {
return pageData;
}
public void setPageData(List<T> pageData) {
this.pageData = pageData;
}
}
设置实体类,在这里以Employee类为例,需要注意的一点,属性名称必须和数据库一致,因为我们使用了dbutils组件。
package entity;
public class Employee {
private int empId;
private String empName;
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
}
下面进行dao的开发,创建EmployeeDao,这里主要去做的事情就是往pagebean里面封装数据
public class EmployeeDao {
public void getAll(PageBean<Employee> pb) {
//查询总记录数,设置到pb对象
int totalCount = getTotalCount();
pb.setTotalCount(totalCount);
//当前页为首页,点击上一页会出现问题,在这里判断,末页同理
if(pb.getCurrentPage() <= 0){
pb.setCurrentPage(1);
}else if(pb.getCurrentPage()>pb.getTotalPage()){
pb.setCurrentPage(pb.getTotalPage());
}
//获取当前页,计算查询起始行,返回的行数
int currentPage = pb.getCurrentPage();
int start = (currentPage - 1) * pb.getPageCount();
int end = pb.getPageCount();
//分页查询数据,把查到的数据设置到pb对象
String sql = "select * from employee limit ?,?";
QueryRunner qr = JdbcUtils.getQueryRunner();
try {
//当前页的数据
List<Employee> list = qr.query(sql, new BeanListHandler<Employee>(Employee.class), start,end);
pb.setPageData(list);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int getTotalCount() {
String sql = "select count(*) from employee";
QueryRunner qr = JdbcUtils.getQueryRunner();
try {
Long count = qr.query(sql, new ScalarHandler<Long>());
return count.intValue();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
接下来进行service的开发,对dao里面的方法进行调用
public class EmployeeService {
private EmployeeDao employeeDao = new EmployeeDao();
public void getAll(PageBean<Employee> pb){
try {
employeeDao.getAll(pb);
} catch (Exception e) {
e.printStackTrace();
}
}
}
然后进行servlet开发,需要注意,首次访问没有任何,需要判断当前页是否存在,如果不存在,则设置当前页为1
public class EmployeeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private EmployeeService employeeService = new EmployeeService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取当前页
try {
String currentPage =req.getParameter("currentPage");
//判断
if(currentPage == null || "".equals(currentPage) ){
currentPage = "1";
}
int realCurrentPage = Integer.parseInt(currentPage);
//创建pageBean对象,设置当前页参数,传入service
PageBean<Employee> pageBean = new PageBean<Employee>();
pageBean.setCurrentPage(realCurrentPage);
employeeService.getAll(pageBean);
//保存pageBean到request域对象中
req.setAttribute("pageBean", pageBean);
//转发
req.getRequestDispatcher("/list.jsp").forward(req, resp);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
最后进行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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>分页</title>
</head>
<body>
<table align="center" border="1" cellpadding="5" cellspacing="0" width="80%">
<tr>
<td>编号</td>
<td>员工编号</td>
<td>员工姓名</td>
</tr>
<c:choose>
<c:when test="${not empty requestScope.pageBean.pageData }">
<c:forEach var="employee" items="${requestScope.pageBean.pageData }" varStatus="vs">
<tr>
<td>${vs.count }</td>
<td>${employee.empId }</td>
<td>${employee.empName }</td>
</tr>
</c:forEach>
</c:when>
<c:otherwise>
<tr>
<td colspan="3">对不起,没有你要找的数据</td>
</tr>
</c:otherwise>
</c:choose>
<tr>
<td colspan="3" align="center">
当前${requestScope.pageBean.currentPage }/${requestScope.pageBean.totalPage }页
<a href="${pageContext.request.contextPath }/employeeServlet?currentPage=1">首页</a>
<a href="${pageContext.request.contextPath }/employeeServlet?currentPage=${requestScope.pageBean.currentPage -1} ">上一页</a>
<a href="${pageContext.request.contextPath }/employeeServlet?currentPage=${requestScope.pageBean.currentPage+1}">下一页</a>
<a href="${pageContext.request.contextPath }/employeeServlet?currentPage=${requestScope.pageBean.totalPage}">末页</a>
</td>
</tr>
</table>
</body>
</html>
ok,大功告成。