實現一個簡單的分頁
阿新 • • 發佈:2018-12-12
此分頁為利用java實現的簡單的分頁,利用jstl和c3p0、dbutils工具、利用maven管理jar包
使用的是資料庫為mysql表為students
宣告此為簡單的展示分頁而已,且程式碼實現不全面,只是展示簡單的實現原理,可以在此demo上進行修改擴充套件
下圖為此demo的目錄結構
maven的pom.xml部分程式碼如下
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency> <dependency> <groupId>commons-dbutils</groupId> <artifactId>commons-dbutils</artifactId> <version>1.6</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> </dependencies>
一個簡單的資料庫
demo的目錄結構
entity目錄下的javabean程式碼如下
package com.ccx.entity; import java.io.Serializable; public class Student implements Serializable { private Integer id; private String name; private Double sal; public Student() { } public Student(Integer id, String name, Double sal) { this.id = id; this.name = name; this.sal = sal; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getSal() { return sal; } public void setSal(Double sal) { this.sal = sal; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", sal=" + sal + '}'; } }
utils工具類JdbcUtils類
package com.ccx.utils; import com.mchange.v2.c3p0.ComboPooledDataSource; import org.apache.commons.dbutils.QueryRunner; public class JdbcUtils { private static ComboPooledDataSource dataSource; static { dataSource=new ComboPooledDataSource(); } public static QueryRunner getQueryRunner(){ return new QueryRunner(dataSource); } }
utils工具類的PageBean類
package com.ccx.utils;
import java.util.List;
/**
* 封裝分頁的引數
* @author ccx
* @param <T>
*/
public class PageBean<T> {
//當前頁,預設顯示第一頁
private Integer currentPage=1;
//每頁顯示的頁數
private Integer pageCount=4;
//總記錄數,就是資料庫的資料總量
private Integer totalCount;
//總頁數=總記錄數/每頁顯示的頁數
private Integer totalPage;
//分頁查詢到的資料
private List<T> pageData;
/**
* 返回總頁數
* @return totalPage
*/
public Integer getTotalPage(){
if (totalCount%pageCount==0){
totalPage=totalCount/pageCount;
}else{
totalPage=totalCount/pageCount+1;
}
return totalPage;
}
public Integer getCurrentPage() {
return currentPage;
}
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
public Integer getPageCount() {
return pageCount;
}
public void setPageCount(Integer pageCount) {
this.pageCount = pageCount;
}
public Integer getTotalCount() {
return totalCount;
}
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
}
public List<T> getPageData() {
return pageData;
}
public void setPageData(List<T> pageData) {
this.pageData = pageData;
}
}
C3P0的配置檔案c3p0-config.xml
<c3p0-config>
<default-config>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/test
</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="user">root</property>
<property name="password">123456</property>
<property name="initialPoolSize">3</property>
<property name="maxPoolSize">6</property>
<property name="maxIdleTime">1000</property>
</default-config>
</c3p0-config>
dao層的StudentDaoImp和StudentDao程式碼如下
package com.ccx.dao;
import com.ccx.entity.Student;
import com.ccx.utils.PageBean;
public interface StudentDaoImp {
/**
* 分頁查詢資料
* @param pageBean
*/
public void getAll(PageBean<Student> pageBean);
/**
* 查詢總記錄數
* @return totalCount
*/
public Integer getTotalCount();
}
package com.ccx.dao.imp;
import com.ccx.dao.StudentDaoImp;
import com.ccx.entity.Student;
import com.ccx.utils.JdbcUtils;
import com.ccx.utils.PageBean;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import java.util.List;
public class StudentDao implements StudentDaoImp {
@Override
public void getAll(PageBean<Student> pageBean) {
Integer totalCount = this.getTotalCount();
pageBean.setTotalCount(totalCount);
Integer currentPage = pageBean.getCurrentPage();
Integer index=(currentPage-1)*pageBean.getPageCount();
Integer count=pageBean.getPageCount();
if(pageBean.getCurrentPage()<=0){
pageBean.setCurrentPage(1);
}else if(pageBean.getCurrentPage()>pageBean.getTotalPage()){
pageBean.setCurrentPage(pageBean.getTotalPage());
}
String sql="SELECT * FROM student LIMIT ?,?";
try{
QueryRunner queryRunner = JdbcUtils.getQueryRunner();
List<Student> studentList = queryRunner.query(sql, new BeanListHandler<Student>(Student.class), index, count);
pageBean.setPageData(studentList);
}catch(Exception e){
e.printStackTrace();
}
}
@Override
public Integer getTotalCount() {
String sql="SELECT COUNT(1) FROM student";
try{
QueryRunner queryRunner = JdbcUtils.getQueryRunner();
Long query = queryRunner.query(sql, new ScalarHandler<Long>());
return query.intValue();
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
service層的StudentServiceImp和StudentService程式碼如下
package com.ccx.service;
import com.ccx.entity.Student;
import com.ccx.utils.PageBean;
public interface StudentServiceImp {
/**
* 分頁資料查詢
* @param pageBean
*/
public void getAll(PageBean<Student> pageBean);
}
package com.ccx.service.imp;
import com.ccx.dao.StudentDaoImp;
import com.ccx.dao.imp.StudentDao;
import com.ccx.entity.Student;
import com.ccx.service.StudentServiceImp;
import com.ccx.utils.PageBean;
public class StudentService implements StudentServiceImp {
private StudentDaoImp studentDao=new StudentDao();
@Override
public void getAll(PageBean<Student> pageBean) {
try{
studentDao.getAll(pageBean);
}catch(Exception e){
e.printStackTrace();
}
}
}
controller層的PageAtcion程式碼如下
package com.ccx.controller;
import com.ccx.entity.Student;
import com.ccx.service.StudentServiceImp;
import com.ccx.service.imp.StudentService;
import com.ccx.utils.PageBean;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/paging")
public class PagingAction extends HttpServlet {
private StudentServiceImp service = new StudentService();
private String url;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
try{
String currentPage = req.getParameter("currentPage");
if(currentPage==null||"".equals(currentPage.trim())){
currentPage="1";
}
Integer index= Integer.valueOf(currentPage);
PageBean<Student> studentPageBean = new PageBean<>();
studentPageBean.setCurrentPage(index);
service.getAll(studentPageBean);
req.setAttribute("pageBean",studentPageBean);
url="/index.jsp";
}catch(Exception e){
e.printStackTrace();
url="/error.jsp";
}
req.getRequestDispatcher(url).forward(req,resp);
}
}
接下來是展示頁面index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>$Title$</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.main{
width: 800px;
height: 500px;
margin: 50px auto;
background: yellow;
}
table{
width: 800px;
height: 500px;
text-align: center;
font-size: 20px;
}
a{
text-decoration: none;
color: #000;
margin-right: 10px;
}
</style>
</head>
<body>
<div class="main">
<table border="1" align="center" cellpadding="5" cellspacing="0">
<tr>
<td>序號</td>
<td>員工編號</td>
<td>員工姓名</td>
<td>員工工資</td>
</tr>
<!-- 迭代資料 -->
<c:choose>
<c:when test="${not empty requestScope.pageBean.pageData}">
<c:forEach var="stu" items="${requestScope.pageBean.pageData}" varStatus="vs">
<tr>
<td>${vs.count }</td>
<td>${stu.id }</td>
<td>${stu.name}</td>
<td>${stu.sal}</td>
</tr>
</c:forEach>
</c:when>
<c:otherwise>
<tr>
<td colspan="4">對不起,沒有你要找的資料</td>
</tr>
</c:otherwise>
</c:choose>
<tr>
<td colspan="4" align="center">
當前${requestScope.pageBean.currentPage }/${requestScope.pageBean.totalPage }頁
<a href="${pageContext.request.contextPath }/paging?currentPage=1">首頁</a>
<a href="${pageContext.request.contextPath }/paging?currentPage=${requestScope.pageBean.currentPage-1}">上一頁 </a>
<a href="${pageContext.request.contextPath }/paging?currentPage=${requestScope.pageBean.currentPage+1}">下一頁 </a>
<a href="${pageContext.request.contextPath }/paging?currentPage=${requestScope.pageBean.totalPage}">末頁</a>
</td>
</tr>
</table>
</div>
</body>
</html>
執行結果如下