Servlet+JavaBean+JSP真假分頁技術詳解

說明:分頁技術分爲真分頁和假分頁,具體採用哪種技術需要根據需求自我抉擇。其實兩者之間實現區別並不是太大。在分頁之前我們需要搞明白對誰進行分頁,一般情況是將數據封裝到一個list集合中,明白這這一點問題基本上就已經解決了。(編寫匆促如有錯誤請聯繫我)

下面首先介紹真分頁。

 

方法一:

爲了大家學習起來方便, 我將在項目中用到的內容都放在這個文檔中,所以可能會比較蘿莉囉嗦。

1.構建數表,字段如下


goods
goodidint
goodnamevarchar(45)
priceflaot


2,建立實體類

   

 privateintgoodsid;//物品編號
    private String goodsname;
    privatefloatprice;//單價
//省略getXXX,與setXXX方法


3,編寫utils工具類,實現數據庫的連接(該工具類比較粗糙,沒有借鑑的價值,之方便學習分頁使用)

publicclass DbConnection {
    privatestatic Connection conn=null;
    private String driver="com.mysql.jdbc.Driver";
    private String url="jdbc:mysql://localhost:3306/mydata";
    private String user="root";
    private String password="123";
    private DbConnection()
    {
        try {
            Class.forName(driver);
            conn=DriverManager.getConnection(url,user,password);
        } catch(ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e){
            e.printStackTrace();
        }      
    }
    publicstatic ConnectiongetConnection()
    {
        if(conn==null)
            new DbConnection();
        returnconn;
    }
    }

 

4,編寫DAO

publicclass Dao {
    privatestatic Connection conn;
    privatestatic ResultSet rs=null;
    privatestatic Statement stmt,stmt1;
    privatestaticintpagesize=5;
    static  {
        conn=DbConnection.getConnection();
       
    }
    publicstatic ResultSetExecuteQuery(String sql)
    {
        try {
            stmt=conn.createStatement();
            rs=stmt.executeQuery(sql);
        } catch (SQLException e){
            e.printStackTrace();
        }
        returnrs;
    }
     //分頁邏輯
    publicstatic  ArrayList<Goods> getGoodsList(int currentpageno) throws SQLException
    {
        ArrayList<Goods>GoodsList=newArrayList<Goods>();
        int BeginRecord=(currentpageno-1)*pagesize;
        int EndRecord=pagesize;//備註,注意,該處表示的是從BeginRecord開始查詢幾個數據,而不代表結束的位置。
        rs=ExecuteQuery("select *from goods limit "+BeginRecord+","+EndRecord);
        try {
            while(rs.next())
            {
                Goodsgoods=new Goods();
                goods.setGoodsid(rs.getInt(1));
                goods.setGoodsname(rs.getString(2));
                goods.setPrice(rs.getFloat(3));
                GoodsList.add(goods);
            }
        } catch (SQLException e){
            e.printStackTrace();
        }
        return GoodsList;
         
    }
    //返回總頁數
    publicstaticint getPageCount()
    {
        int total=0;
        int PageCount=0;
        try {
            rs=stmt.executeQuery("selectcount(*) from goods");
            if(rs.next())
            {
                total=rs.getInt(1);
                PageCount=(total-1)/pagesize+1;
            }
        } catch (SQLException e){
            e.printStackTrace();
        }
        return PageCount;
    }
}

  


5servlet

publicvoiddoPost(HttpServletRequest request,HttpServletResponse response)
            throws ServletException,IOException {
        Stringpageno=request.getParameter("currentpageno");
        int currentpageno=1;
        if(pageno!=null){
            currentpageno=Integer.parseInt(pageno);
        }
        ArrayList<Goods>GoodsList=null;
        try {
            GoodsList = Dao.getGoodsList(currentpageno);
            System.out.println(GoodsList.size()); 
        } catch (SQLException e){
            e.printStackTrace();
        }
        request.setAttribute("GoodsList", GoodsList);
        request.setAttribute("currentpageno", currentpageno);
        request.setAttribute("PageCount",Dao.getPageCount());//設置總共頁數
        request.getRequestDispatcher("/LimiteGoods.jsp").forward(request, response);
    }

6jsp表示層

<%@ pagelanguage="java"contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 
<!DOCTYPE htmlPUBLIC "-//W3C//DTDHTML 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>分頁技術Demo</title>
<script type="text/javascript">
function jumptopage()
{  
 
    var inputnode=document.getElementById("jumptopage");
    var page=inputnode.value;
    if(isNaN(page))
    {
        alert("請輸入正整數");
        }
    else if(page>${PageCount})
        return;
        else
        {
    window.location="/Mypage/servlet/GetLimiteGoods?currentpageno="+page;
    }
}
 
</script>
 </head>
 <body>
 <center>
    
  <table width="80%" border="1" height="56">
    <tr align="center">
       <td>
         商品編號
        </td>
       <td>
         商品名稱
        </td>
       <td>
         商品價格
        </td>
      </tr>
     <c:forEach var="goods" items="${GoodsList}">
    <tr align="center">
       <td>
          ${goods.goodsid}
         </td>
        <td> 
          ${goods.goodsname}
        </td>
        <td> 
        ${goods.price}
        </td>
    </tr>
</c:forEach>
</table>
 <c:if test="${currentpageno>1}">
   <a href="/Mypage/servlet/GetLimiteGoods?currentpageno=1">首頁</a>
   <a href="/Mypage/servlet/GetLimiteGoods?currentpageno=${currentpageno-1}">上一頁</a>
  </c:if>
    <font color="blue">當前爲 ${currentpageno}頁</font>
  <c:if test="${PageCount>currentpageno}">
   <a href="/Mypage/servlet/GetLimiteGoods?currentpageno=${currentpageno+1}">下一頁</a>
   <a href="/Mypage/servlet/GetLimiteGoods?currentpageno=${PageCount}">尾頁</a>
  </c:if>
    跳轉到第<input type="text" id="jumptopage"   style="width:15px;">頁
    <input type="button" value="go" onclick="jumptopage()">
    </center>
</body>
</html>

 

      


真分頁部分結束

第二部分,假分頁的實現

1,數據表,Bean,util與第一部分相同,不再重複

2,dao層做稍微的修改

publicstatic  ArrayList<Goods> getGoodsList(int currentpageno) throws SQLException
    {
        ArrayList<Goods>GoodsList=newArrayList<Goods>();
        rs=ExecuteQuery("select * from goods");//改變的地方
                try {
            while(rs.next())
            {
                Goodsgoods=new Goods();
                goods.setGoodsid(rs.getInt(1));
                goods.setGoodsname(rs.getString(2));
                goods.setPrice(rs.getFloat(3));
                GoodsList.add(goods);
            }
        } catch (SQLException e){
            e.printStackTrace();
        }
        return GoodsList;
    }

Dao層返回頁數部分函數不再需要

3,servlet層部分修改

publicvoiddoPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException,IOException {
       int pagesize=5;//增加項
      int pageCount;//增加項
        Stringpageno=request.getParameter("currentpageno");
        int currentpageno=1;
        if(pageno!=null){
            currentpageno=Integer.parseInt(pageno);
        }
        ArrayList<Goods>GoodsList=null;
        ArrayList<Goods>gl=newArrayList<Goods>();//增加項
        try {
            GoodsList = Dao.getGoodsList(currentpageno);
            Iterator<Goods>it=GoodsList.iterator();
           //---------------------------------修改部分
            int i=0;
            for(i=0;i<(currentpageno-1)*5;i++)
                it.next();
                   for(i=0;i<5;i++)
            {
               
                gl.add((Goods)it.next());
            }
               //---------------------------------修改部分        
        } catch (SQLException e){
            e.printStackTrace();
        }
        pageCount=(GoodsList.size()-1)/pagesize+1;
        request.setAttribute("GoodsList", gl);//修改部分
        request.setAttribute("currentpageno", currentpageno);
        request.setAttribute("PageCount",pageCount );
        request.getRequestDispatcher("/LimiteGoods.jsp").forward(request,response);
    }

         

4,jsp層和上文相同,不再重複。

5,另附web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee"xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID"version="2.5">
  <display-name>Mypage</display-name>
  <servlet>
    <servlet-name>GetLimiteGoods</servlet-name>
    <servlet-class>servlet.GetLimiteGoods</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>GetLimiteGoods</servlet-name>
    <url-pattern>/servlet/GetLimiteGoods</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>servlet/GetLimiteGoods</welcome-file>
    <welcome-file>servlet/GetLimiteGoods</welcome-file>
    <welcome-file>servlet/GetLimiteGoods</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <filter>
  <display-name>CharFilter</display-name>
    <filter-name>CharFilter</filter-name>
    <filter-class>Filter.CharFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>CharFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

    


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章