mysql分页查询

1,创建一个Page类,getset方法


2.查询出数据库所需要分页的数据总数目totalCount


3.计算 总页数 totalPage,总 数目已经得到,当前页数和 每页显示的数目是前端传过来的,看下图发现规律

总数/每页显示的数目 的结果 往上靠一点 就是总页数 可以利用 Math.ceil方法计算得出

总数     每页现实数目     总页数
9          10        0.9     1
10         10                1
11         10        1.1     2

//2.根据 总数目 和 当前 显示数目 计算总页数
int totalPage = (int) Math.ceil(1.0 * totalCount / currentCount);

4.把得到的数据全封装到Page类中

5.在利用limit函数之前 ,计算出起始位置

公式:(当前页数 -1 )*每页显示的数目

/*
    页数         每页显示的条数         起始位置
    1            3                        0
    2             3                       3
    3             3                       6
 */
//4.计算起始位置
int startIndex = (currentPage - 1) * currentCount;

6.利用 limit函数

ComboPooledDataSource dataSource = new ComboPooledDataSource();
QueryRunner queryRunner = new QueryRunner(dataSource);
String sql = "SELECT * FROM category LIMIT ?,?";
List<Category> list = queryRunner.query(sql, new BeanListHandler<Category>(Category.class), startIndex, currentCount)
7.
//6.将集合 封装到page类中
page.setList(findPageList);

8.将数据 返回到前端,前端分页可以用Bootstrap来做

<nav>
    <ul class="pagination">
        <li>
            <a  href="#" aria-label="Previous" >
                <span aria-hidden="true">«</span>
            </a>
        </li>

        <li >
            <a  href="#" aria-label="Previous" >
                <span aria-hidden="true"></span>
            </a>
        </li>

        <c:forEach begin="1" end="${page.totalCount}" varStatus="status">
            <li>
                <a href="?start=${status.index}" class="current">${status.count}</a>
            </li>

        </c:forEach>

        <li >
            <a href="#" aria-label="Next">
                <span aria-hidden="true"></span>
            </a>
        </li>
        <li >
            <a href="#" aria-label="Next">
                <span aria-hidden="true">»</span>
            </a>
        </li>
    </ul>
</nav>


























posted @ 2018-06-28 21:17  王某人i  阅读(457)  评论(0编辑  收藏  举报