Fork me on GitHub

分页

刚刚在网上查看了一下,分页算法网上都给一些案例,可是大都不是下载不了就是安装不了,于是小博怒刷一把,果断分享自己的源码

链接http://pan.baidu.com/s/1eQcXFnO 密码:hwik,可以进去链接中下载数据库源代码

这个案例里面有的代码很多,我分析一下给大伙听听

                                                              

                                                              

1.我们主要用到的的有①DbConnection,②news.java,③newlist.jsp,④pageService.jsp,有一些类【StringConvert.java】是因为new.java中需要进行格式转换才用到的。我们暂时可以忽略!

2.DbConnection.java,连接数据库,注意:root,password,的“具体值”得改称为你的数据库的配置。

 1 package com.henu.util;
 2 
 3 import java.sql.Connection;
 4 import java.sql.SQLException;
 5 import java.util.Properties;
 6 
 7 import org.apache.commons.dbcp.BasicDataSource;
 8 import org.apache.commons.dbcp.BasicDataSourceFactory;
 9 
10 public class DbConnection {
11     private static BasicDataSource dataSource = null;
12     /**
13      * 初始化数据库连接池
14      */
15     public static void init() 
16     {
17         if (dataSource != null)
18         {
19             try
20             {
21                 dataSource.close();
22             } catch (Exception e)
23             {
24                 e.printStackTrace();
25             }
26             dataSource = null;
27         }
28         //使用Properties对象定义数据库连接池信息
29         try {
30             Properties p = new Properties();
31             p.setProperty("driverClassName", "com.mysql.jdbc.Driver");
32             p.setProperty("url", "jdbc:mysql://localhost:3306/newsdb");
33             p.setProperty("username", "root");
34             p.setProperty("password", "123456");
35             p.setProperty("maxActive", "30");
36             p.setProperty("maxIdle", "10");
37             p.setProperty("maxWait", "1000");
38            //以指定信息创建数据源
39             dataSource = (BasicDataSource) BasicDataSourceFactory.createDataSource(p);
40         } catch (Exception e) {
41             e.printStackTrace();
42         }
43     }
44     /**
45      * 从连接池中获取连接
46      * @return
47      * @throws SQLException
48      */
49     public static synchronized Connection getConnection() throws  SQLException {
50         if (dataSource == null) {
51             init();
52         }
53         Connection conn = null;
54         if (dataSource != null) {
55             conn = dataSource.getConnection();
56         }
57         return conn;
58     }
59 }

3.news.java  其实就是一个javabean,暂时存放数据的地点而已!

  1 package com.henu.bean;
  2 import java.util.Date;
  3 import java.sql.*;
  4 
  5 import com.henu.util.StringConvert;
  6 public class news {
  7     private int id;
  8     private String username;
  9     private String title;
 10     private String content;
 11     private String attachment;
 12     private int viewCount;
 13     private Date submitTime;
 14     private String catalogs;
 15     
 16     private String keywords;
 17     private String searchType;
 18 
 19 
 20     public void setId(int id)
 21     {
 22         this.id = id;
 23     }
 24     public int getId()
 25     {
 26         return this.id;
 27     }
 28     
 29     public void setUsername(String username)
 30     {
 31         this.username = username;
 32     }
 33     public String getUsername()
 34     {
 35         return this.username;
 36     }
 37     
 38     public void setTitle(String title)
 39     {
 40         this.title = StringConvert.convert(title);
 41     }
 42     public String getTitle()
 43     {
 44         return this.title;
 45     }
 46     
 47     public void setContent(String content)
 48     {
 49         this.content = StringConvert.convert(content);
 50     }
 51     public String getContent()
 52     {
 53         
 54         return this.content;
 55     }
 56     
 57     public void setAttachment(String Attachment)
 58     {
 59         this.attachment = Attachment;
 60     }
 61     public String getAttachment()
 62     {
 63         return this.attachment;
 64     }
 65     
 66     public void setCatalogs(String Catalogs)
 67     {
 68         this.catalogs = StringConvert.convert(Catalogs);
 69     }
 70     public String getCatalogs()
 71     {
 72         return this.catalogs;
 73     }
 74     
 75     public void setViewCount(int ViewCount)
 76     {
 77         this.viewCount = ViewCount;
 78     }
 79     public int getViewCount()
 80     {
 81         return this.viewCount;
 82     }
 83 
 84     public void setSubmitTime(Date SubmitTime)
 85     {
 86         this.submitTime = SubmitTime;
 87     }
 88     public Date getSubmitTime()
 89     {
 90         return this.submitTime;
 91     }
 92     
 93     public void setKeywords(String k)
 94     {
 95         this.keywords = StringConvert.convert(k);
 96     }
 97     public String getKeywords()
 98     {
 99         return this.keywords;
100     }
101     public void setSearchType(String s)
102     {
103         this.searchType = StringConvert.convert(s);
104     }
105     public String getSearchType()
106     {
107         return this.searchType;
108     }

 

4.newList.jsp,只要用于显示界面

  1 <%@ page language="java" contentType="text/html; charset=gbk" import="com.henu.bean.news,com.henu.util.*,java.sql.*"
  2     pageEncoding="gbk"%>
  3 <%
  4     int i;
  5     ResultSet rs;
  6     //每页显示的记录数
  7     int pageSize = 10;
  8     //总页数
  9     int pageCount;
 10     //当前页码
 11     int pageCurrent;
 12     //总记录数
 13     int totalRecord;
 14     //临时变量,获得页面参数
 15     String pages;
 16     String sql = "SELECT * FROM `newsdb`.`news` ORDER BY submitTime DESC";
 17     pages = request.getParameter("page");
 18     if(pages == null)
 19         pageCurrent = 1;
 20     else
 21         {
 22             pageCurrent = Integer.parseInt(pages);
 23             //当前页码最小只能为1
 24             if(pageCurrent < 1)
 25                 pageCurrent = 1;
 26         }
 27     //连接数据库
 28     Connection con = DbConnection.getConnection();
 29     Statement s = con.createStatement();
 30     
 31     rs = s.executeQuery(sql);
 32     //获取总记录数
 33     rs.last();
 34     totalRecord = rs.getRow();
 35     //计算总页数
 36     pageCount = ((totalRecord % pageSize == 0) ? (totalRecord /pageSize) : (totalRecord / pageSize)+1);
 37     
 38     if(pageCurrent > pageCount)
 39         pageCurrent = pageCount;
 40 %>
 41 <html>
 42 <head>
 43 <title>分页显示</title>
 44 </head>
 45 <body>
 46 <table width="800">
 47 <tr><th width="500">标题</th><th width="150">发布人</th><th width="150">日期</th></tr>
 48 <%
 49     if( pageCount > 0)
 50     {
 51         //使ResultSet的指针定位到当前页的第一条记录
 52         rs.absolute((pageCurrent - 1) * pageSize + 1);
 53         //显示该记录
 54         i = 0;
 55         while( i < pageSize && ! rs.isAfterLast())
 56         {
 57 %>
 58 <tr>
 59 <td width="500"><%=rs.getString("title") %></td>
 60 <td width="150"><%=rs.getString("username") %></td>
 61 <td width="150"><%=rs.getDate("submitTime") %></td>
 62 </tr>
 63 <%
 64          rs.next();
 65          i++;
 66         }
 67     }
 68 %>
 69 </table>
 70 <center>
 71 当前第<%=pageCurrent %>页,共<%=pageCount %> 72 <%
 73 //以下实现翻页
 74 //如果当前页码大于1,则为“上一页”加链接
 75 if(pageCurrent > 1)
 76 {
 77 %>
 78 <a href="newsList.jsp?page=<%=pageCurrent-1 %>">上一页</a>    
 79 
 80 <%
 81 }
 82 else
 83 {
 84 %>
 85 上一页
 86 <%
 87 }
 88 //如果当前页码小于总页数,则为“下一页”加链接
 89 if(pageCurrent < pageCount)
 90 {    
 91 %>
 92 <a href="newsList.jsp?page=<%=pageCurrent+1 %>">下一页</a>
 93 <%
 94 }
 95 else        
 96 {
 97 %>
 98 下一页
 99 <%
100 }
101 %>
102 </center>
103 <%
104     //关闭连结
105     rs.close();
106     con.close();
107 %>
108 </center>
109 </body>
110 </html>

5.pageService.jsp其实就是一个分页类,用于获取分页 

  1 package com.henu.util;
  2 import java.util.ArrayList;
  3 import java.util.List;
  4 import javax.servlet.http.HttpServletRequest;
  5 import javax.servlet.http.HttpServletResponse;
  6 import javax.servlet.http.HttpSession;
  7 /**
  8  * 分页类,用于获取分页
  9  * 【更新说明】
 10  * 1,增加属性:isReverse Boolean类型,用于控制是否反转记录
 11  * 2,page方法增加参数:key String类型,用于指定存入session中的集合的属性名
 12  * 3,改进了分页算法
 13  * 【bug修改说明】
 14  * 1,修正了设置参数无效的问题
 15  * 2,修正了记录顺序异常的问题
 16  * 3,修正了无法在footer链接中增加查询字符串的问题
 17  * 
 18  */
 19 public class PageService {    
 20     private int pageId = 1;// 表示当前请求的分页号    
 21     private int pageSize = Integer.MAX_VALUE; // 每页显示的记录数
 22     private int rows; // 记录总数
 23     private int total; // 总共的页数    
 24     private boolean isReverse = false;
 25     public int getPageId() {
 26         return pageId;
 27     }
 28     public void setPageId(int pageId) {
 29         if (pageId <= 0) {
 30             pageId = 1;
 31         }
 32         this.pageId = pageId;
 33     }
 34     public int getPageSize() {
 35         return pageSize;
 36     }
 37     public void setPageSize(int pageSize) {
 38         this.pageSize = pageSize;
 39     }
 40     public void setRows(List list) {
 41         this.rows = list.size();
 42     }
 43     public int getRows() {
 44         return rows;
 45     }        
 46     public boolean isReverse() {
 47         return isReverse;
 48     }
 49     public void setReverse(boolean isReverse) {
 50         this.isReverse = isReverse;
 51     }
 52     public void setTotal(List list) {// 该方法用来求得,总共的页数
 53         total = list.size() / pageSize;// 该语句用来求得除pageSize的整数
 54         int e = list.size() % pageSize;// 该语句用来求得相除后的余数
 55         if (e != 0) {// 如果余数不为零,则total加一
 56             this.total = this.total + 1;
 57         }
 58         //total表示总页数
 59         //total = (this.total%pageSize==0?this.total/pageSize:this.total/pageSize + 1);
 60         
 61     }
 62     public int getTotal() {
 63         return total;
 64     }
 65     /**
 66      * 取得当前页码所对应的记录
 67      * @param page_Id <code>String</code>类型 页码
 68      * @param pageSize 每页的大小(显示的条目的数目)
 69      * @param alllist 所有的记录的集合
 70      * @return 应该在页面中读取的条目的集合
 71      */
 72     public List getPage(String page_Id,int pageSize,List allList){
 73         if(null == page_Id){
 74             page_Id = "1";
 75         }
 76         //设置请求分页号
 77         setPageId(Integer.parseInt(page_Id));
 78         //设置分页的记录数
 79         setPageSize(pageSize);
 80         //设置记录总数
 81         setRows(allList);
 82         //设置总共的页数
 83         setTotal(allList);
 84         int start = 0;
 85         int end = 0;
 86         ArrayList tempList  = new ArrayList();
 87         if(this.isReverse)
 88         {
 89             for(int i = allList.size() ; i>0; i--)
 90             {
 91                 tempList.add(allList.get(i-1));
 92             }
 93         }
 94         else
 95         {
 96             tempList = (ArrayList) allList;
 97         }
 98         List res = new ArrayList();
 99         int countAll = allList.size();
100         
101         if(total<=1){//如果最大页数小于等于一,也就是说其实只有一页
102             start = 0 ;
103             end = countAll;
104         } else if(pageId < total){ //如果请求的页码小于最大页数
105             start = (pageId - 1) * pageSize;
106             end = pageId * pageSize;
107         } else if(pageId >= total){ //如果请求的页码大于等于最大页数
108             start = (pageId - 1) * pageSize;
109             end = countAll;
110         }        
111         res = tempList.subList(start, end);
112         return res;
113     }
114         
115     /**
116      * 显示页码导航
117      * @param path 请求页面的完整URL,不要带查询字符串
118      * @param action 需呀在请求URL额外增加的查询字符串,以“&”开头(参考范例<code>"&command=key"</code>),如果无参数请留空
119      * @return
120      */
121     public String getPageFooter(String path,String action){ 
122         if(action==null)
123         {
124             action = "";
125         }
126         String str = "";
127         int to_tal =total-(total-1); 
128         int next, prev;
129         prev = pageId - 1;
130         next = pageId + 1;
131         if(pageId>1){
132             str += "<a href="+path+"&pageId=" + to_tal + action +">首页</a>&nbsp;&nbsp;";
133         }else{
134             str += "";
135         }
136         if(pageId>1){
137             str += "<a href="+path+"&pageId=" + prev + action +">&lt;&lt;上一页</a>&nbsp;&nbsp;";
138         }else{
139             str += "";
140         }
141         if(pageId<total){
142             str += "<a href="+path+"&pageId=" + next + action+">下一页&gt;&gt;</a>&nbsp;&nbsp;";
143         }else{
144             str += "";
145         }
146         if(pageId<total){
147             str += "<a href="+path+"&pageId=" + total + action+">尾页</a>&nbsp;&nbsp;";
148         }else{
149             str += "";
150         }
151         str += "当前第<font color ='blue'>"+pageId+"</font>页&nbsp;&nbsp共<font color ='blue'>"+total+"</font>页&nbsp;&nbsp;总<font color ='blue'>"+rows+"</font>条";
152         return str;
153     }
154     /**
155      * 将一个页面需要显示的条目的集合写入session对象中
156      * @param request 
157      * @param response
158      * @param list 全部的条目的集合
159      * @param pagemethod 查询字符串,请不要以“?”开头,参考范例:<code>"command=key"</code>
160      * @param key 当前页面条目的对象的属性名
161      */
162     public void page(HttpServletRequest request, HttpServletResponse response,List list,String pagemethod,String key) 
163     {
164         
165         //取得当前的页码
166         String pageId = request.getParameter("pageId");
167         String footer = "";
168         //每页显示的记录
169         List pageList = this.getPage(pageId, pageSize, list);    
170         footer = this.getPageFooter(request.getRequestURI()+"?"+pagemethod,"");
171         HttpSession session = request.getSession();
172         session.setAttribute(key,pageList);
173         session.setAttribute("footer", footer);
174     }
175 }

基本就是这样子。

因为源代码中有涉及到上传下载;图标显示等问题, 因为主要与本主题无关,暂时跳过!有问题可以联系我,zzzzw!

 

                                                                                                                                    

posted @ 2015-05-20 16:32  ZZZZW  阅读(291)  评论(0编辑  收藏  举报
AmazingCounters.com