你的位置:首页 > Java教程

[Java教程]jsp分页


 

1,分页的原理:

通常我们从数据库取得的数据较多时不会全部展现出来,需要用到分页。

2,怎么取到我们所需要的数据呢?

*处理分页请求的Servlet或者jsp

*请求要显示页面的页码

*每页显示的信息数

*总页数

3,分页分为两大类:

*内存分页:一次将所有的页面查询出来,然后根据页面的请求显示指定的记录数。

*sql分页:根据页面的请求一次只从数据库中读取一页的结果,然后在页面显示该页。(select *from table limit 开始位置,结束位置)

下面开始进行分页实战:

1,首先我们创建一个page封装类,

 

 1 package cn.com.yong.Pojo; 2  3 import java.util.List; 4  5 public class Page { 6   private int count;//总条数 7   private List<Announcement> evCount;//显示的数据 8   private int pageSize=6;//每页的条数 9   @SuppressWarnings("unused")10   private int pageCount;//总页数11   private int pageNow;//当前页12   public Page(){}13   public Page(int count, List<Announcement> evCount, int pageSize,14       int pageCount, int pageNow) {15     this.count = count;16     this.evCount = evCount;17     this.pageSize = pageSize;18     this.pageCount = pageCount;19     this.pageNow = pageNow;20   }21   public int getCount() {22     return count;23   }24   public void setCount(int count) {25     this.count = count;26   }27   public List<Announcement> getEvCount() {28     return evCount;29   }30   public void setEvCount(List<Announcement> evCount) {31     this.evCount = evCount;32   }33   public int getPageSize() {34     return pageSize;35   }36   37   public int getPageCount() {38     int i=0;39     if(getCount()%getPageSize()==0){40       i=getCount()/getPageSize();41     }else{42       i=getCount()/getPageSize()+1;43     }44     return i;45   }46   public void setPageCount(int pageCount) {47     this.pageCount = pageCount;48   }49   public int getPageNow() {50     return pageNow;51   }52   public void setPageNow(int pageNow) {53     this.pageNow = pageNow;54   }55   56   57 }

2.我们写一个接口,加上我们需要实现的方法

1 public interface AnnouncementDao {2   3   public Page getListPage(Page page);4   5 }

3.实现接口

 1 public class AnnouncementDaoImplement implements AnnouncementDao{ 2 public Page getListPage(Page page) { 3     int coun=0;
      //创建list对象,用来存储查询到的数据库数据 4 List<Announcement> list=new ArrayList<Announcement>();
      //与数据库建立联系(通过单列设计模式实现,文章最后会附上) 5 con=DBConnection.getDBConnectionInstance().getDBConnection();
      //查询总记录数 6 String sql="select count(*) from announcement";
      //按照要求查询需要的记录 两个问号分别代表起始位置和结束位置 7 String sql2="select id,title,context from announcement limit ?,?"; 8 try { 9 ps=con.prepareStatement(sql2);
        //下标从零开始,需要-110 ps.setInt(1, (page.getPageNow()-1)*page.getPageSize());11 ps.setInt(2, page.getPageSize());12 ResultSet rs2=ps.executeQuery();13 while(rs2.next()){14 Announcement an=new Announcement();15 an.setId(rs2.getInt(1));16 an.setTitle(rs2.getString(2));17 an.setContext(rs2.getString(3));
           //把查询到的数据添加到list集合里18 list.add(an);19 }20 rs=con.createStatement().executeQuery(sql);21 if(rs.next()){22 coun=rs.getInt(1);23 24 }
        //把得到的list集合设置给page的成员变量EvCount25 page.setEvCount(list);
        //查询到的总记录数附给count26 page.setCount(coun);27 28 } catch (SQLException e) {29 e.printStackTrace();30 }31 return page;32 33 }34 35 }

4,创建一个Servlet

import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import cn.com.yong.DaoImplement.AnnouncementDaoImplement;import cn.com.yong.Pojo.Page;@WebServlet("/AnnouncementFindAllServlet")public class AnnouncementFindAllServlet extends HttpServlet {  private static final long serialVersionUID = 1L;  Page page=null;  public void doGet(HttpServletRequest request, HttpServletResponse response)      throws ServletException, IOException {      doPost(request, response);      }  public void doPost(HttpServletRequest request, HttpServletResponse response)      throws ServletException, IOException {    //创建一个session对象    HttpSession session=request.getSession();
    //获取实现类中的参数page,得到里面的数据 page=(Page)session.getAttribute("page"); if(page==null){ page=new Page(); } int pageNow=0;
     //获取当前页的属性 String str=request.getParameter("pageNow"); if(str==null){ pageNow=1; }else{ pageNow=Integer.parseInt(str); }
         //把当前页得到的数值赋给page类中的pagenow变量 page.setPageNow(pageNow); AnnouncementDaoImplement adi=new AnnouncementDaoImplement(); //调用方法 page=adi.getListPage(page);
      //    为page设置属性让jsp页面能够接受这个属性 session.setAttribute("page", page); response.sendRedirect("AnnouncementSelectAll.jsp"); }}

5,jsp页面

 1 <% 2 String path = request.getContextPath(); 3 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 4 Page pa=(Page)session.getAttribute("page"); 5 %> 6  7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9  <head> 10   <base href="<%=basePath%>"> 11    12   <title>My JSP 'AnnouncementDao.jsp' starting page</title> 13    14   <meta http-equiv="pragma" content="no-cache"> 15   <meta http-equiv="cache-control" content="no-cache"> 16   <meta http-equiv="expires" content="0">   17   <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 18   <meta http-equiv="description" content="This is my page"> 19   <script src="jquery-1.6.4.min.js" type="text/javascript"></script> 20   <script type="text/javascript">  21   $(document).ready(function demo(){ 22    23     $("th").css({ color: "black", background: "#DDDDDD" }); 24      25      26   }); 27   function getFirstPage(p){ 28     if(p==1){ 29       alert("你已经在首页了") 30       }else{ 31       window.location.href="AnnouncementFindAllServlet?pageNow=1"; 32         } 33     } 34   function getLastPage(p){ 35     var last=<%=pa.getPageCount()%>; 36     if(p==last){ 37       alert("你已经在尾页了"); 38       }else{ 39       window.location.href="AnnouncementFindAllServlet?pageNow="+last; 40         } 41     } 42   function getPageUp(p){ 43     if(p==1){ 44     alert("你已经在首页了"); 45       }else{ 46         window.location.href="AnnouncementFindAllServlet?pageNow="+(p-1); 47         } 48     } 49   function getPageDn(p){ 50     var last=<%=pa.getPageCount()%>; 51     if(p==last){ 52     alert("你已经在尾页了"); 53       }else{ 54         window.location.href="AnnouncementFindAllServlet?pageNow="+(p+1); 55         } 56     } 57   function getJumpPage(pn){ 58     var changePage = document.getElementById("jumpPage").value; 59     if(changePage ==-1){ 60       alert("请选择你要跳转的页面"); 61     }else if(changePage==pn){ 62       alert("您已经在该页"); 63     }else{ 64       window.location.href="AnnouncementFindAllServlet?pageNow="+changePage; 65     } 66   } 67   </script> 68  </head> 69   70  <body> 71   <p id="one" >公告管理</p> 72   <p >____________________________________________________________________________________________________</p> 73  <table align="center" width="100%" border="1" cellpadding="1" cellspacing="1" > 74     <tr> 75       <th>公告编号</th> 76       <th>公告标题</th> 77       <th>操作</th> 78     </tr> 79   <%   80   81     for(Announcement an:pa.getEvCount()){ 82        83   %> 84      85      86     <tr align="center"> 87       <td><%=an.getId()%></td> 88       <td><%=an.getTitle()%></td> 89       <td><a href="AnnouncementDelServlet?id=<%=an.getId()%>">删除</a>|| 90       <a href="AnnouncementUpdateServlet?id=<%=an.getId()%>">修改</a></td> 91        92     </tr> 93      94   <%} %> 95   </table> 96     <p>共<%=pa.getPageCount()%>页,当前第<%=pa.getPageNow()%>页   97     <span id="firstPage" onclick="getFirstPage(<%=pa.getPageNow()%>)">首页</span> 98     <span id="pageUp" onclick="getPageUp(<%=pa.getPageNow()%>)">上一页</span> 99     <span id="pageDn" onclick="getPageDn(<%=pa.getPageNow()%>)">下一页</span>100     <span id="lastPage" onclick="getLastPage(<%=pa.getPageNow()%>)">尾页</span>101     <span>102     <span>跳转到103           <select id="jumpPage" onchange="getJumpPage(<%=pa.getPageNow() %>)">104             <option value="-1">--请选择--</option>105             <%106               for(int i=1;i<=pa.getPageCount();i++){107             %>108               <option value="<%=i%>"><%=i%></option>109             <% }%>110           </select>111           页</span>112     </span>113     </p>114  </body>115 </html>

附:jdbc单例

public class DBConnection {  private String url="jdbc:mysql://localhost:3306/ei";  private String user="root";  private String password="666888";  private Connection con=null;  //构造方法私有化  private DBConnection(){    try {      Class.forName("com.mysql.jdbc.Driver");      con=DriverManager.getConnection(url, user, password);    } catch (ClassNotFoundException e) {      e.printStackTrace();    } catch (SQLException e) {      e.printStackTrace();    }  }  //创建一个私有化对象  private static DBConnection jdbc=new DBConnection();  //实例  public static DBConnection getDBConnectionInstance(){    return jdbc;  }  public Connection getDBConnection() {    return con;  }}