首页 > 代码库 > Ajax分页插件Pagination从前台jQuery到后端java总结

Ajax分页插件Pagination从前台jQuery到后端java总结

前端代码.html

    var pageSize = 10;//设置每页显示条数
        var total;//数据总条数
        function pagination() {
            $("#Pagination").pagination(total, {
                callback : PageCallback,
                prev_text : ‘上一页‘,
                next_text : ‘下一页‘,
                items_per_page : pageSize,
                num_display_entries : 4, //连续分页主体部分显示的分页条目数
                num_edge_entries : 1
            //两侧显示的首尾分页的条目数
            })
        }
        function PageCallback(index, jq) { //前一个表示您当前点击的那个分页的页数索引值,后一个参数表示装载容器。 
            LoadData(index);
        }
        function LoadData(pageIndex) {
            $.ajax({
                type : "get",
                url : "servlet/BookServlet?p=0&pageSize=" + pageSize
                        + "&pageIndex=" + pageIndex,
                async : false,
                dataType : "json",
                success : function(ObjData) {
                    var lists = ObjData.data;
                    total = ObjData.recordsTotal;
                    $("#tbodyList").empty();
                    $("#listsTemplate").tmpl(lists).appendTo("#tbodyList");
                }
            })
        }
$(function() {
            LoadData(0);//分页初始化
            pagination();//分页展示
})
    <div id="Pagination" class="pagination">
                                                <!-- 这里显示分页 -->
                                            </div>

PageHelper帮助类

package com.rongjie.common;

import java.util.ArrayList;
import java.util.List;

/**
 * 分页帮助类
 * @author 曹勇
 *
 * @param <T> javabean class
 */
public class PageHelper<T> {
    private List<T> list;//返回数据集合
    private int total;//查询数据总数

    public List<T> getList() {
        return list;
    }

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

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    /**
     * 分页算法
     * @param list 总数据
     * @param page 当前页码
     * @param rows 每页容量
     * @return List
     * 注: 次方法应用于数据量比较小的情况,反之 会很慢
     */
    public List<T> paginationBook(List<T> list, int page, int rows) {
        List<T> small = new ArrayList<T>();
        int beginIndex = rows * page;
        int endIndex;
        if (rows * (page + 1) > list.size()) {
            endIndex = list.size();
        } else {
            endIndex = rows * (page + 1);
        }
        for (int i = beginIndex; i < endIndex; i++) {
            small.add(list.get(i));
        }
        return small;
    }
}

 

Servlet代码 这部分非通用代码。根据项目自行调整

protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        String pageIndex = request.getParameter("pageIndex");// 当前页码
        int page = (RegExpValidatorUtils.IsNumber(pageIndex) == true) ? Integer.parseInt(pageIndex) : 0;
        String pageSize = request.getParameter("pageSize");// 每页显示多少条
        int rows = (RegExpValidatorUtils.IsNumber(pageSize) == true) ? Integer.parseInt(pageSize) : 0;
        BookViewInfo bookViewInfo = null;//这个是 视图bean,可根据自己需求修改
        PageHelper<BookInfo> plist = null;//分页帮助类
        plist = bll.Index(page, rows);//调用业务层 方法
        List<BookViewInfo> bookViewInfoList = new ArrayList<BookViewInfo>();
        // 装载视图 模型
        for (BookInfo bookInfo : plist.getList()) {//这部分是 装载对象,根据不同项目 要进行修改
            bookViewInfo = new BookViewInfo();
            bookViewInfo.setBook_id(bookInfo.getBook_id());
            String statusTemp = bookInfo.getBook_status();
            bookViewInfo.setBook_status(statusTemp);
            bookViewInfo.setBook_title(bookInfo.getBook_title());
            bookViewInfo.setBook_category(bookInfo.getBook_category());
            bookViewInfo.setBook_saleprice(bookInfo.getBook_saleprice());
            bookViewInfo.setBook_createtime(sdf.format(bookInfo.getBook_createtime()));
            bookViewInfo.setBook_creator(bookInfo.getBook_creator());
            bookViewInfo.setCategory_name(bookInfo.getCategoryInfo().getCategory_name());
            bookViewInfoList.add(bookViewInfo);
        }
        Collections.reverse(bookViewInfoList);// 倒序
        String jsonStr = "{\"recordsTotal\":" + plist.getTotal() + ",\"recordsFiltered\":" + bookViewInfoList.size()
                + ",\"data\":" + JSONArray.fromObject(bookViewInfoList) + "}"; //这里使用了 net.sf.json.JSONArray 来做json序列化
        response.getWriter().write(jsonStr);
    }

业务层代码:这部分非通用代码。根据项目自行调整

private BookDao dao = new BookDao();

    /**
     * 分页数据
     * 
     * @param page
     *            当前页码
     * @param rows
     *            每页显示多少条数据
     * @return
     */
    public PageHelper<BookInfo> Index(int page, int rows) {
        PageHelper<BookInfo> pageHelper = new PageHelper<BookInfo>();
        List<BookInfo> alllist = dao.Index();
        pageHelper.setTotal(alllist.size());// 数据总量
        List<BookInfo> list = pageHelper.paginationBook(alllist, page, rows);
        pageHelper.setList(list);// 每次装在rows数量的数据
        Collections.reverse(list);// 倒序
        return pageHelper;
    }

DAO层代码  这部分非通用代码。根据项目自行调整

/**
     * 查询所有图书
     * 
     * @return List
     */
    public List<BookInfo> Index() {
        String sql = "select * from  表 ";
        try {
            jdbcUtils = new JdbcUtils();
            connection = jdbcUtils.getConnection();// 连接数据库

            List<BookInfo> list = findAll(sql);

            return list;
        } catch (Exception e) {
            throw new DaoException(e);
        } finally {
            jdbcUtils.releaseConn(connection, null);
        }
    }
/**
     * 分页查询 /查询全部信息
     * 
     * @param sql
     *            查询语句
     * @param params
     * @return
     * @throws SQLException
     * @throws ParseException
     */
    private List<BookInfo> findAll(String sql, Object... params) throws SQLException, ParseException {
        List<BookInfo> list = new ArrayList<BookInfo>();
        pstmt = connection.prepareStatement(sql);
        setParam(pstmt, params);
        resultSet = pstmt.executeQuery();

        // Timestamp book_createtime = new
        // Timestamp(System.currentTimeMillis());
        // book_createtime = Timestamp.valueOf(book_createtimeStr);
        while (resultSet.next()) {
            BookInfo bookInfo = new BookInfo();
            CategoryInfo categoryInfo = new CategoryInfo();
            bookInfo.setID(resultSet.getInt("id"));
            bookInfo.setBook_id(resultSet.getInt("book_id"));
            bookInfo.setBook_category(resultSet.getInt("book_category"));
            bookInfo.setBook_publisher(resultSet.getInt("book_publisher"));
            bookInfo.setBook_publishtime(resultSet.getDate("book_publishtime"));
            bookInfo.setBook_title(resultSet.getString("book_title"));
            // 构造以字符串内容为值的BigDecimal类型的变量book_price
            BigDecimal book_price = new BigDecimal(resultSet.getString("book_price"));
            BigDecimal book_saleprice = new BigDecimal(resultSet.getString("book_saleprice"));
            // 设置小数位数,第一个变量是小数位数,第二个变量是取舍方法(四舍五入)
            book_price = book_price.setScale(2, BigDecimal.ROUND_HALF_UP);
            book_saleprice = book_saleprice.setScale(2, BigDecimal.ROUND_HALF_UP);
            bookInfo.setBook_price(book_price);
            bookInfo.setBook_saleprice(book_saleprice);
            bookInfo.setBook_isbn(resultSet.getString("book_isbn"));
            bookInfo.setBook_supplier(resultSet.getString("book_supplier"));
            bookInfo.setBook_keyword(resultSet.getString("book_keyword"));
            bookInfo.setBook_summary(resultSet.getString("book_summary"));
            bookInfo.setBook_cover(resultSet.getString("book_cover"));
            bookInfo.setBook_preview(resultSet.getString("book_preview"));
            bookInfo.setBook_download(resultSet.getString("book_download"));
            bookInfo.setBook_creator(resultSet.getInt("book_creator"));
            bookInfo.setBook_createtime(resultSet.getTimestamp("book_createtime"));
            bookInfo.setBook_status(resultSet.getString("book_status"));
            categoryInfo.setCategory_name(resultSet.getString("category_name"));
            bookInfo.setCategoryInfo(categoryInfo);
            list.add(bookInfo);
        }
        jdbcUtils.releaseConn(connection, resultSet);
        return list;
    }

 

Ajax分页插件Pagination从前台jQuery到后端java总结