1. 程式人生 > >Java分頁管理的實現【原始操作】

Java分頁管理的實現【原始操作】

分頁功能的實現:

  • 物理分頁:一次只查指定條記錄,點選下一頁,再去查詢後指定條.使用SQL語句進行控制的分頁.
    • 缺點:經常需要和資料庫互動.
    • 優點:資料量特別大,不會導致記憶體的溢位.
  • 邏輯分頁:一次性將所有資料全都查詢出來,根據需要進行擷取.List集合進行控制. subList();
    • 缺點:資料量如果特別大,容易導致記憶體溢位.
    • 優點:與資料庫互動次數少.

實現詳解

  • 不同的資料庫對分頁的語句也是不一樣的:

    • MYSQL進行分頁: 使用limit關鍵字.
      • select * from xxx where .. Group by … Having … Order by … limit a,b; – a:從哪開始 b:查詢的記錄數.
      • 根據頁數計算 limit後面的兩個引數:
        • currPage begin pageSize
          1 0 10
          2 10 10
          3 20 10
        • begin = (currPage - 1) * pageSize;
    • 引數的傳遞:
      • 前臺—>後臺:currPage
      • 後臺—>前臺:currPage,totalPage(總頁數),totalCount(總記錄數),pageSize,List集合.
    • 使用JavaBean封裝引數:
      • 後臺—>前臺:傳遞一個JavaBean就可以.
    • Oracle進行分頁: 使用SQL語句巢狀.
    • SQL Server資料庫進行分頁: 使用 top 關鍵字.
  • 在首頁上新增一個分頁查詢的連結:

關鍵程式碼實現

//service層處理邏輯,JavaBean就不寫了
    public PageBean findPage(int currPage) throws SQLException {
        PageBean pageBean = new PageBean();
        // 設定當前頁數
        pageBean.setCurrPage(currPage);
        //設定每頁顯示的記錄數
int pageSize=10; pageBean.setPageSize(pageSize); //設定總的記錄數 ProductDAO productDAO = new ProductDAO(); int count = productDAO.findCount(); pageBean.setTotalCount(count); //設定總的頁數 Double pageNum = Math.ceil(count/pageSize); pageBean.setTotalPage(pageNum.intValue()); //每頁顯示的記錄集合boub int begin = (currPage-1)*pageSize; List<Product> list = productDAO.findByPage(begin,pageSize); pageBean.setList(list); return pageBean; } //DAO層實現: public List<Product> findByPage(int begin, int pageSize) throws SQLException { //建立查詢物件 QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource()); String sql = "select * from product order by pdate limit ?,?"; List<Product> list = queryRunner.query(sql, new BeanListHandler<Product>(Product.class),begin,pageSize); return list; } public int findCount() throws SQLException { //建立查詢物件 QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource()); //查詢總的記錄數 String sql = "select count(*) from product "; Long count = (Long) queryRunner.query(sql, new ScalarHandler()); return count.intValue(); } //servlet層的實現 //post提交亂碼處理問題 request.setCharacterEncoding("utf-8"); // 接收資料 Product product = new Product(); Map<String, String[]> map = request.getParameterMap(); //封裝資料 BeanUtils.populate(product, map); //呼叫業務層處理資料 ProductService service = new ProductService(); List<Product> list = service.findproduct(product); //響應瀏覽器 request.setAttribute("lsit", list); request.getRequestDispatcher("/jsp/product_page.jsp").forward(request, response);

JSP頁面的實現:使用jstl,需要匯入兩個jar包,引入標籤庫程式碼實現如下:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="${ pageContext.request.contextPath }/js/jquery-1.8.3.js"></script>
<script type="text/javascript">
    function addPage(){
        window.location.href="${ pageContext.request.contextPath }/jsp/addProduct.jsp";
    }

    function del(pid){
        var flag = window.confirm("您確定刪除這條記錄嗎?");
        if(flag == true){
            window.location.href="${ pageContext.request.contextPath }/ProductDeleteServlet?pid="+pid;
        }
    }

    function delAll(){
        document.getElementById("form1").submit();
    }

    function search(){
        // 獲得文字框的值:
        var pname = document.getElementById("pname").value;
        // 獲得表單:
        document.getElementById("form1").action="${ pageContext.request.contextPath }/ProductSearchServlet";
        // 表單提交:
        document.getElementById("form1").submit();
    }

    $(function(){
        $("#selectAll").click(function(){
            $("input[id='ids']").prop("checked",this.checked);
        });
    });
</script>
</head>
<body>
<h1>商品的列表頁面</h1>
<form id="form1" action="${ pageContext.request.contextPath }/ProductDeleteAllServlet" method="post">
<table border="1" width="800">
    <tr>
        <td colspan="8">
            名稱:<input type="text" id="pname" name="pname"><input type="button" value="查詢" onclick="search()">&nbsp;&nbsp;&nbsp;&nbsp;
            <input type="button" value="新增" onclick="addPage()"/>&nbsp;&nbsp;&nbsp;&nbsp;
            <input type="button" value="刪除" onclick="delAll()"/>&nbsp;&nbsp;&nbsp;&nbsp;
        </td>   
    </tr>
    <tr>
        <td>序號</td>
        <td><input type="checkbox" id="selectAll" /></td>
        <td>商品名稱</td>
        <td>市場價格</td>
        <td>商城價格</td>
        <td>是否熱門</td>
        <td>是否下架</td>
        <td>操作</td>
    </tr>
    <c:forEach var="p" items="${ pageBean.list }" varStatus="status">
    <tr>
        <td>${ status.count }</td>
        <td><input type="checkbox" id="ids" name="ids" value="${ p.pid }"/></td>
        <td>${ p.pname }</td>
        <td>${ p.market_price }</td>
        <td>${ p.shop_price }</td>
        <td>
            <c:if test="${ p.is_hot == 1 }"></c:if>
            <c:if test="${ p.is_hot == 0 }"></c:if>
        </td>
        <td>
            <c:if test="${ p.pflag == 1 }">
                已下架
            </c:if>
            <c:if test="${ p.pflag == 0 }">
                未下架
            </c:if>
        </td>
        <td><a href="${ pageContext.request.contextPath }/ProductEditServlet?pid=${p.pid}">修改</a>|<a href="#" onclick="del('${p.pid}')">刪除</a></td>
    </tr>
    </c:forEach>
    <tr>
        <td colspan="8" align="center">
            第${ pageBean.currPage }/${ pageBean.totalPage }頁&nbsp;&nbsp;
            總記錄數:${ pageBean.totalCount }&nbsp;每頁顯示的記錄數:${ pageBean.pageSize }&nbsp;&nbsp;
            &nbsp;&nbsp;
            <c:if test="${ pageBean.currPage != 1 }">
            <a href="${ pageContext.request.contextPath }/ProductFindByPageServlet?currPage=1">[首頁]</a>
            <a href="${ pageContext.request.contextPath }/ProductFindByPageServlet?currPage=${ pageBean.currPage - 1 }">[上一頁]</a>
            </c:if>
            &nbsp;&nbsp;

            <c:forEach var="i" begin="1" end="${ pageBean.totalPage }">
                <c:if test="${ pageBean.currPage != i }">
                    <a href="${ pageContext.request.contextPath }/ProductFindByPageServlet?currPage=${i}">${ i }</a>
                </c:if>
                <c:if test="${ pageBean.currPage == i }">
                    ${ i }
                </c:if>
            </c:forEach>

            &nbsp;&nbsp;
            <c:if test="${ pageBean.currPage != pageBean.totalPage }">
            <a href="${ pageContext.request.contextPath }/ProductFindByPageServlet?currPage=${ pageBean.currPage + 1}">[下一頁]</a>
            <a href="${ pageContext.request.contextPath }/ProductFindByPageServlet?currPage=${ pageBean.totalPage }">[尾頁]</a>
            </c:if>
        </td>   
    </tr>
</table>
</form>
</body>