案例:怎样使用java实现分页处理?

数据库表格:

  customer

分页的实现:

从数据库查询--总记录:totalRecords

自定义--每页显示多少条记录: pageSize

通过总记录数和页容量计算出来--总页数: totalPages ----(totalRecords%pageSize==0? totalRecords/pageSize : totalRecords/pageSize+1)

页面传递--当前页码: currentPage

从数据库查询--每页数据:List

通过当前页数和页容量计算出来--每页查询开始的索引 startIndex startIndex = (currentPage-1)*pageSize

bean

public class Page {
    private long totalRecords;//总记录数   从数据库查询
    private long pageSize=5;//每页显示多少条
    private long totalPages;//总页数    计算出来
    private long currentPage;//当前页码
    private List list; //每页存放的数据   从数据库查询
    private long startIndex;//每页开始查询的索引 计算出来

    public Page(long currentPage,long totalRecords){
        this.currentPage = currentPage;
        this.totalRecords = totalRecords;
        this.totalPages = (totalRecords%pageSize==0?  totalRecords/pageSize : totalRecords/pageSize+1);
        this.startIndex = (currentPage-1)*pageSize;
    }

    public long getTotalRecords() {
        return totalRecords;
    }

    public void setTotalRecords(long totalRecords) {
        this.totalRecords = totalRecords;
    }

    public long getPageSize() {
        return pageSize;
    }

    public void setPageSize(long pageSize) {
        this.pageSize = pageSize;
    }

    public long getTotalPages() {
        return totalPages;
    }

    public void setTotalPages(long totalPages) {
        this.totalPages = totalPages;
    }

    public long getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(long currentPage) {
        this.currentPage = currentPage;
    }

    public List getList() {
        return list;
    }

    public void setList(List list) {
        this.list = list;
    }

    public long getStartIndex() {
        return startIndex;
    }

    public void setStartIndex(long startIndex) {
        this.startIndex = startIndex;
    }

}

Dao.Impl

public class CustomerDaoImpl implements CustomerDao{
    QueryRunner qr = new QueryRunner(C3p0Util.getDataSource());
    //显示列表
    public List<Customer> findCustomers() {
        String sql = "select * from customer";
        List<Customer> clist = new ArrayList<Customer>();
        try {
            clist = qr.query(sql, new BeanListHandler<Customer>(Customer.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return clist;
    }
    //查询每页记录数据
    public List<Customer> findPageCustomers(long startIndex, long pageSize) {
        String sql = "select * from customer limit ?,?";
        Object[] params = {startIndex,pageSize};
        List<Customer> clist = new ArrayList<Customer>();
        try {
            clist = qr.query(sql, new BeanListHandler<Customer>(Customer.class),params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return clist;
    }
    //查询总记录数
    public long findCustomersCount() {
        String sql  = "select count(1) from customer";
        long  i= 0;
        try {
            i = (Long)qr.query(sql, new ScalarHandler(1));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i;
    }
}

Service.Impl

public class CustomerServiceImpl implements CustomerService{
    private CustomerDao dao = new CustomerDaoImpl();
    //显示列表
    public List<Customer> findCustomers() {
        return dao.findCustomers();
    }
    //与页码相对应的每个列表
    public Page findPage(long currentPage) {
        long totalRecords = dao.findCustomersCount();//总记录数
        Page page = new Page(currentPage, totalRecords);
        List<Customer> clist = dao.findPageCustomers(page.getStartIndex(), page.getPageSize());
        page.setList(clist);
        return page;
    }
}
Servlte(在web.xml里设置默认页面为servlte页面)
/**
 * servlet页面
 * @author Administrator
 *下午1:56:49
 */
public class CustomerAction extends HttpServlet {
    private CustomerService service = new CustomerServiceImpl();
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String currentPageStr = request.getParameter("pagenum"); //从网页上获取跳转的页数
        int currentPage = 1;  //默认显示第一页
        if(currentPageStr!=null){
            currentPage = Integer.parseInt(currentPageStr);
        }
        Page page = service.findPage(currentPage);//显示与页码相对应的列表
        request.setAttribute("page", page);
        request.getRequestDispatcher("WEB-INF/jsp/clist.jsp").forward(request, response);

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

jsp(由servlet处理后转发至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>
<c:set var="ctp" value="${pageContext.request.contextPath }"></c:set>
<script type="text/javascript" src="${ctp }/js/jquery-1.8.3.js"></script>
</head>
<body>
    <h2>客户列表</h2>
    <table border="1" width="80%">
        <tr>
            <th>序号</th>
            <th>姓名</th>
            <th>性别</th>
            <th>生日</th>
            <th>电话</th>
            <th>邮箱</th>
            <th>爱好</th>
            <th>类型</th>
            <th>描述</th>
        </tr>
        <c:forEach items="${page.list }" var="ct" varStatus="cs">     <!--使用迭代标签库 -->
            <tr style="background-color: ${cs.count%2==0? ‘#E0FFFF‘:‘#EEE685‘}">
                <td>${cs.count }</td>
                <td>${ct.name }</td>
                <td>${ct.gender==1? ‘男‘:‘女‘ }</td>
                <td>${ct.birthday }</td>
                <td>${ct.phone }</td>
                <td>${ct.email }</td>
                <td>${ct.hobby }</td>
                <td>${ct.type }</td>
                <td>${ct.description }</td>
            </tr>
        </c:forEach>
    </table>
    <p>
        总记录数:${page.totalRecords }条
        当前第${page.currentPage }页/共${page.totalPages }页
        <a href="${ctp }/customerAction?pagenum=1">首页</a>
        <a href="${ctp }/customerAction?pagenum=${page.currentPage-1<1? 1 : page.currentPage-1}">上一页</a>
        <a href="${ctp }/customerAction?pagenum=${page.currentPage+1<page.totalPages? page.currentPage+1 : page.totalPages}">下一页</a>
        <a href="${ctp }/customerAction?pagenum=${page.totalPages}">尾页</a>
        <input id="num" placeholder="请输入整数"/><input type="button" id="btn" value="跳转"/>
        <input id="pages" value="${page.totalPages }" type="hidden">
    </p>
    <!--使用jQuery简单判定跳转的页数是否合法-->
    <script type="text/javascript">
        $(function(){
            $("#btn").click(function(){
                var pageNum = Number($("#num").val());
                var pages = Number($("#pages").val());
                if(isNaN(pageNum)){
                    alert("请输入数字!");
                    return;
                }
                if(pageNum > pages){
                    alert("输入页码错误!");
                    return;
                }
                location.href = "${ctp}/customerAction?pagenum="+pageNum;
            });
        });
    </script>

</body>
</html>

效果图:

注:省略dao层、service层、c3p0连接池工具包

时间: 2024-07-28 17:56:29

案例:怎样使用java实现分页处理?的相关文章

java超强分页标签演示

最近在做一个项目,用到了一个分页,于是动手写了个分页标签,先将代码贴出来,供大家交流,写的不好,请见谅!. 以下是java标签类,继承自SimpleTagSupport [java] view plaincopyprint? package com.lynn.oa.tag; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.jsp.JspExcep

JAVA实现分页

JAVA实现分页有三种方式: 1:使用list接口中的Sublist实现分页            效率低 2:直接使用数据库SQL语句实现分页(mysql中用limit关键字,oracle用rownum关键字)   数据库兼容性差 3: hibernate框架实现跨数据库分页  兼容不同数据库 但是复杂查询性能低 使用Hibernate 创建Query对象,查询时设置firstResult和MaxResuit属性

01_JNI是什么,为什么使用,怎么用JNI,Cygwin环境变量配置,NDK案例(使用Java调用C代码)

1 什么是JNI JNI Java本地开发接口 JNI是一个协议,这个协议用来沟通java代码和外部的本地代码(C/C++) 通过这个协议,java代码就可以调用外部的C/C++代码,外部的C/C++代码也可以调用Java代码. 2 为什么用JNI 1  JNI扩展了java虚拟机的能力,驱动开发(wifi-hotspot)2.3无线热点共享 2  Native code效率高,数学运算,实时渲染的游戏上,音视频处理(极品飞车),opengl,ffmpeg 3  复用代码(文件压缩,人脸识别)

java 关于分页的实现

 关于java实现分页 转自:http://www.cnblogs.com/slliang/archive/2012/08/22/2651053.html 1.分页工具类,封装分页信息 package com.student.util; import java.util.List; import com.student.entity.Person; /** * 封装分页信息 * @author Administrator * * @param <Person> */ public class

java内存分页

List<BofCytProduct> bofCytProductArray=getAllOnProdcuct(); List<BofCytProduct> list = new ArrayList<BofCytProduct>(); for(BofCytProduct bofCytProduct:bofCytProductArray){ if(!ProductCodeConstants.JI_JIN.equals(bofCytProduct.getTypeCode()

java MongoDB分页优化

最近项目在做网站用户数据新访客统计,数据存储在MongoDB中,统计的数据其实也并不是很大,1000W上下,但是公司只配给我4G内存的电脑,让我程序跑起来气喘吁吁...很是疲惫不堪. 最常见的问题莫过于查询MongoDB内存溢出,没办法只能分页查询.这种思想大家可能都会想到,但是如何分页,确实多有门道! 网上用的最多的,也是最常见的分页采用的是skip+limit这种组合方式,这种方式对付小数据倒也可以,但是对付上几百上千万的大数据,却只能望而兴叹... 经过网上各种查找资料,寻师问道的,发现了

java web 分页技术

查询界面,通过姓名和车号进行查询,然后将查询结果提交给servlet: <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.

springmvc+java+mysql分页条件查询自学代码

jsp: <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <% String path = request.getContextPath(); String b

JAVA实战教程_JAVA案例开发之JAVA开发微信二维码大数据开发03

大家好,这次是第三个课时的视频,欢迎大家继续学习. 视频简介:本视频是关于JAVA实战教程,JAVA开发微信二维码大数据系统.这个JAVA开发案例可以协助一些从零基础开始学习JAVA,正处于理论走完实践的路程上的初学者能接触到实际开发项目过程中,在实践当中巩固自己的JAVA方面的知识外,更能在项目案例当中学到解决在JAVA学习或者实践当中遇上问题的一些解决方式.仅供参考!自设交流群:457036818,欢迎一起加入交流. PS:该案例共十个课时,本小节为第二课时 课程原地址:http://www