1. 程式人生 > >javaweb編寫分頁mysql

javaweb編寫分頁mysql

java分頁

1.封裝PageBean

import java.util.List;

/**
 * 分頁的JavaBean
 * @author Administrator
 */
public class PageBean<T> {

    // 當前頁
    private int pageCode;

    // 總頁數
    // private int totalPage;

    // 總記錄數
    private int totalCount;
    // 每頁顯示的記錄條數
    private int pageSize;
    // 每頁顯示的數據
    private List<T> beanList;

    public int getPageCode() {
        return pageCode;
    }
    public void setPageCode(int pageCode) {
        this.pageCode = pageCode;
    }

    /**
     * 調用getTotalPage() 獲取到總頁數
     * JavaBean的屬性規定:totalPage是JavaBean是屬性 ${pageBean.totalPage}
     * @return
     */
    public int getTotalPage() {
        // 計算
        int totalPage = totalCount / pageSize;
        // 說明整除
        if(totalCount % pageSize == 0){
            return totalPage;
        }else{
            return totalPage + 1;
        }
    }

    /*public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }*/

    public int getTotalCount() {
        return totalCount;
    }
    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }
    public int getPageSize() {
        return pageSize;
    }
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }
    public List<T> getBeanList() {
        return beanList;
    }
    public void setBeanList(List<T> beanList) {
        this.beanList = beanList;
    }
}

2.Servlet

/**
     * 獲取當前頁
     *如果用戶沒有傳,默認是第一頁,如果傳了,就是幾
     * @param request
     * @return
     */
    public int getPageCode(HttpServletRequest request){
        String pc = request.getParameter("pc");
        // 判斷
        if(pc == null || pc.trim().isEmpty()){
            return 1;
        }
        return Integer.parseInt(pc);
    }
/**
     * 分頁查詢
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /**
         * 處理當前頁
         * 處理每頁顯示的記錄條數
         */
        // 當前頁
        int pageCode = getPageCode(request);
        // 處理每頁顯示的記錄條數
        int pageSize = 4;
        try {
            // 調用業務層,分頁查詢
            PageBean<Product> page = new ProductService().findByPage(pageCode,pageSize);
            // 存入
            request.setAttribute("page", page);
            // 轉發
            request.getRequestDispatcher("/jsp/pages.jsp").forward(request, response);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

3.service

/**
     * 分頁查詢
     * @param pageCode
     * @param pageSize
     * @return
     * @throws SQLException 
     */
    public PageBean<Product> findByPage(int pageCode, int pageSize) throws SQLException {
        return new ProductDao().findByPage(pageCode,pageSize);
    }

4.dao


/**
     * 分頁查詢
     * 
     * @param pageCode
     * @param pageSize
     * @return
     * @throws SQLException 
     */
    public PageBean<Product> findByPage(int pageCode, int pageSize) throws SQLException {
        PageBean<Product> page = new PageBean<>();
        // 屬性是空的
        page.setPageCode(pageCode);
        page.setPageSize(pageSize);

        QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
        // ScalarHandler 處理聚合函數
        long count = (long) qr.query("select count(*) from product", new ScalarHandler());
        // 設置總記錄條數
        page.setTotalCount((int) count);

        // limit a,b a = (當前頁-1) * b
        List<Product> beanList = qr.query("select * from product limit ?,?", new BeanListHandler<Product>(Product.class),
                (pageCode - 1) * pageSize, pageSize);

        // 每頁顯示的數據
        page.setBeanList(beanList);

        return page;
    }

5.utils

public class JdbcUtils {

    // 成員變量,創建了C3P0的連接池(連接池中已經存在連接了...)
    private static final ComboPooledDataSource DATASOURCE = new ComboPooledDataSource();

    /**
     * 返回的是C3P0的連接池
     * @return
     */
    public static DataSource getDataSource(){
        return DATASOURCE;
    }

    /**
     * 獲取連接,返回連接
     * @return
     */
    public static Connection getConnection(){
        Connection conn = null;
        try {
            // 從連接池中來獲取連接,conn 是增強過的連接
            conn = DATASOURCE.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 釋放資源
     * @param stmt
     * @param conn
     */
    public static void release(Statement stmt,Connection conn){
        if(stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn != null){
            try {
                // 已經變成了歸還了...
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 釋放資源
     * @param stmt
     * @param conn
     */
    public static void release(ResultSet rs,Statement stmt,Connection conn){
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn != null){
            try {
                // 把close()給修改了,原來是銷毀連接,現在讓方法變成歸還連接。
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

6.jsp頁面

<table border="1" width="100%">
    <tr>
        <th>序號</th>
        <th>圖片</th>
        <th>名稱</th>
        <th>市場價格</th>
        <th>商城價格</th>
        <th>商品日期</th>
    </tr>

    <c:forEach var="p" items="${ page.beanList }" varStatus="vs">
        <tr align="center">
            <td>${ vs.count }</td>
            <td>
                <img src="${ pageContext.request.contextPath }/${p.pimage}" width="100px" height="100px">
            </td>
            <td>${ p.pname }</td>
            <td>${ p.market_price }</td>
            <td>${ p.shop_price }</td>
            <td>${ p.pdate }</td>
        </tr>
    </c:forEach>

    分頁條 
    <tr>
        <th colspan="6">
            第${ page.pageCode }頁/共${ page.totalPage }頁
            <a href="${ pageContext.request.contextPath }/findByPage?pc=1">首頁</a>
            <c:if test="${ page.pageCode > 1 }">
                <a href="${ pageContext.request.contextPath }/findByPage?pc=${page.pageCode - 1}">上一頁</a>
            </c:if>

                begin和end值是變化的,設置begin和end的值
                邏輯:
                    * 如果總頁數<=10頁,讓begin=1 end=總頁數
                    * 如果總頁數 > 10頁,begin=當前頁-5 ,end = 當前頁 + 4
                        * 頭溢出:如果begin<1,出現了頭溢出了,讓begin=1 end=10
                        * 尾溢出:如果end > 總頁數,讓begin=總頁數-9 end=總頁數

            <c:choose>
                <c:when test="${ page.totalPage <= 10 }">
                    <c:set var="begin" value="1"/>
                    <c:set var="end" value="${ page.totalPage }"/>
                </c:when>
                <c:otherwise>
                    <c:set var="begin" value="${ page.pageCode - 5 }"/>
                    <c:set var="end" value="${ page.pageCode + 4 }"/>
                頭溢出的問題 
                    <c:if test="${ begin < 1 }">
                        <c:set var="begin" value="1"/>
                        <c:set var="end" value="10"/>
                    </c:if>

                    <c:if test="${ end > page.totalPage }">
                        <c:set var="begin" value="${ page.totalPage - 9 }"/>
                        <c:set var="end" value="${ page.totalPage }"/>
                    </c:if>
                </c:otherwise>
            </c:choose>

            <c:forEach var="i" begin="${ begin }" end="${ end }">
                <a href="${ pageContext.request.contextPath }/findByPage?pc=${i}">[${ i }]</a>
            </c:forEach>

            <c:if test="${ page.pageCode < page.totalPage }">
                <a href="${ pageContext.request.contextPath }/findByPage?pc=${page.pageCode + 1}">下一頁</a>
            </c:if>
            <a href="${ pageContext.request.contextPath }/findByPage?pc=${page.totalPage}">尾頁</a>
        </th>
    </tr>
</table>

javaweb編寫分頁mysql