Jsp分页实例
Posted onJsp分页实例
┆ 回首页
Java中文网址大全┆学习笔记┆ java文摘┆ 源码下载 ┆Java实例 ┆ Java教学 ┆ J2me学习┆ 留言板 站内资源搜索: ┆ 将本文寄给朋友 Jsp分页实例
〖 作者:wangxiaoyi2 〗〖 大小:1M 〗〖 发布日期:2010-03-15 〗〖 浏览:0 〗 效果图:
1)数据库操作类,做简单封装 DB.java
package Test;
import java.sql./*;
public class DB {
// 加载驱动 static { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("驱动加载出错"); } }
// 获取数据库连接
public static Connection getConn() { Connection conn = null; try { conn = DriverManager.getConnection("jdbc:mysql://localhost/userinfo?user=root&password=abcd"); } catch (SQLException e) { e.printStackTrace(); } return conn; } // 关闭数据库连接 public static void closeConn(Connection conn) { try { if(conn != null) { conn.close(); conn = null; } } catch (SQLException e) { e.printStackTrace(); } } // 关闭Statement public static void closeStmt(Statement stmt) { try { if(stmt != null) { stmt.close(); stmt = null; } } catch (SQLException e) { e.printStackTrace(); } } // 关闭ResultSet public static void closeRs(ResultSet rs) { try { if(rs != null) { rs.close(); rs = null; } } catch (SQLException e) { e.printStackTrace(); } } } ///////////////////////////////////////////////////////*
2)初始化数据类 initData.java
package Test;
import java.sql./*;
public class initData {
private static Connection conn = null;
private static PreparedStatement pstmt = null;
private static Statement stmt = null;
private static String sql = "insert into userinfo(id,username,age) values(?,?,?)"; // 总条数 private static int allCount = 10000; // 分批条数 private static int preCount = 1000; // 计数器 private static int count = 0;
public static void main(String[] args) { CleanData();// 清除数据 InsertData();// 插入数据 }
/// / DDL语句 建表语句 / create table userinfo ( id int(20) not null, username / varchar(255), age varchar(255), primary key (id) ) //
/// / 插入数据 用addBatch()方法 / 当数据量达到1000时 提交一次 // private static void InsertData() { try { conn = DB.getConn(); pstmt = conn.prepareStatement(sql); conn.setAutoCommit(false); long start = System.currentTimeMillis(); for (int i = 1; i <= allCount; i++) { pstmt.setInt(1, i); pstmt.setString(2, "java" + i); pstmt.setString(3, "20"); pstmt.addBatch(); if ((i % preCount) == 0) { pstmt.executeBatch(); System.out.println("当前进行完毕===>" + (++count) / preCount
+ "条");
}
} long end = System.currentTimeMillis(); System.out.println("数据插入成功!所用时间为: " + (end - start) + " ms"); } catch (Exception e) { e.printStackTrace(); try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } System.out.println("数据出错,已进行回滚"); } finally { try { conn.commit();//提交数据 } catch (SQLException e) { e.printStackTrace(); } DB.closeStmt(pstmt); DB.closeConn(conn); } } /// / 清除数据 // private static void CleanData() { try { conn = DB.getConn(); String sql = "delete from userinfo"; stmt = conn.createStatement(); stmt.executeUpdate(sql); System.out.println(sql); System.out.println("清除数据成功!"); } catch (SQLException e) { e.printStackTrace(); } finally { DB.closeStmt(stmt); DB.closeConn(conn); } } } /////////////////////////////////////////////////////*
3)分页核心类 Pager.java
package Test;
import javax.servlet.http./*;
public class Pager { private int totalRows; // 总行数 private int pageSize = 20; // 每页显示的行数 private int currentPage = 1; // 当前页号 private int totalPages; // 总页数 private int startRow; // 当前页在数据库中的起始行
// 构造方法1 private Pager() { }
// 构造方法2 带参数_totalRows private Pager(int _totalRows) { totalRows = _totalRows; totalPages = totalRows / pageSize; int mod = totalRows % pageSize; if (mod > 0) { totalPages++; } currentPage = 1; startRow = 0; }
// 设置当前页在数据库中的起始行 public void setStartRow(int startRow) { this.startRow = startRow; } // 获取当前页在数据库中的起始行 public int getStartRow() { return startRow; } // 设置总页数 public void setTotalPages() { totalPages = totalRows / pageSize; int mod = totalRows % pageSize; if (mod > 0) { totalPages++; } } // 获取总页数 public int getTotalPages() { return totalPages; } // 设置当前页码 public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } // 获取当前页码 public int getCurrentPage() { return currentPage; } // 设置总行数 public void setTotalRows(int totalRows) { this.totalRows = totalRows; } // 获取总行数 public int getTotalRows() { return totalRows; } // 设置每页显示行数 public void setPageSize(int pageSize) { this.pageSize = pageSize; } // 获取每页显示的行数 public int getPageSize() { return pageSize; } // 首页 public void first() { currentPage = 1; startRow = 0; } // 前一页 public void previous() { if (currentPage == 1) { return; } currentPage--; startRow = (currentPage - 1) / pageSize; } // 下一页 public void next() { if (currentPage < totalPages) { currentPage++; } startRow = (currentPage - 1) / pageSize; } // 最后一页 public void last() { currentPage = totalPages; startRow = (currentPage - 1) /* pageSize; } // 刷新页码 public void refresh(int _currentPage) { currentPage = _currentPage; if (currentPage > totalPages) { last(); } }
/// / 获得下一页的页码 如果当前页码+1大于等于最大页数, / 则下一页的页码为最大页数 否则下一页的页码为当前页码+1 /*/ public int getNext() { if (currentPage +1 >= totalPages) { return totalPages; } else { return currentPage+1 ; } }
// 获取前一页的页码 public int getPrevious() { if (currentPage - 1 <= 1) { return 1; } else { return currentPage - 1; } }
// 判断是否存在下一页 public boolean hasNext() { return currentPage < getTotalPages(); }
// 判断是否存在上一页 public boolean hasPrevious() { return currentPage > 1; }
// 判断是否是第一页 public boolean isFirst() { return currentPage == 1; }
// 判断是否是最后一页 public boolean isLast() { return currentPage == getTotalPages(); }
/// / 产生js代码 / / @param url / @return /*/ public static String getJavascript(String url) { StringBuffer sb = new StringBuffer(); sb.append("function goPage(pageNumber)\r\n"); sb.append("{\r\n"); sb.append(" window.self.location='" + url
+ "?pageNumber='+pageNumber+'&pageSize='+pageSize.value+'';\r\n");
sb.append("}\r\n"); return sb.toString();
}
/// / 产生html代码 / @param total / @return // public String getNavigate(){
setTotalPages();
StringBuffer buf = new StringBuffer();
buf.append("共"+ totalRows+ "条记录 "+ pageSize+ "条/页 "); buf.append("第"+ currentPage+ "页/共"+ totalPages+ "页 ");
// 判断 "首页" 链接是否显示 if(isFirst()){ buf.append("[首页] "); } else{ buf.append("[首页] "); }
// 判断 "上一页" 链接是否显示 if (hasPrevious()) { buf.append("[<a href='javascript:goPage(" + getPrevious()
+ ")' target='_self'>上一页</a>] ");
} else { buf.append(" [上一页] "); }
// 判断 "下一页" 链接是否显示 if (hasNext()) { buf.append("[<a href='javascript:goPage(" + getNext()
+ ")' target='_self'>下一页</a>] ");
} else { buf.append("[下一页] "); }
// 判断 "尾页" 链接是否显示 if(isLast()){ buf.append("[尾页] 转到"); } else{ buf.append("[<a href='javascript:goPage(" + totalPages
+ ")' target='_self'>尾页</a>] 转到");
}
// 转到第几页选择框 // 用onchange方法轻松搞定转向 buf.append("<select name=select' onchange='javascript:goPage(this.options[this.selectedIndex].value)'>");
for (int x = 1; x <= getTotalPages(); x++) { buf.append(""); } buf.append(""); buf.append("每页"); buf.append(" ");
return buf.toString(); }
public static Pager getInstance(HttpServletRequest request,int total){ Pager cPager = new Pager(); String pNum = request.getParameter("pageNumber"); if (pNum == null||pNum == "") pNum = "1"; int intpNum = Integer.parseInt(pNum);
String pSize = request.getParameter("pageSize");
if (pSize == null||pSize == "") pSize = "25";
int intpSize = 0;
try{
intpSize = Integer.parseInt(pSize);
}catch (NumberFormatException nfe){
intpSize = 20;
//nfe.printStackTrace();
}
cPager.currentPage = intpNum;
cPager.pageSize = intpSize;
cPager.totalRows = total;
return cPager; } }
///////////////////////////////////////////////////////////////*
4)UserDAO.java
package Test;
import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList;
public class UserDAO {
///
/ 根据指定的页码范围查找数据
/ @param pageSize
/ @param pageNumber
/ @return
/*/
public static ArrayList
// SQL Server写法 // String sql = "select top " + pageSize + " / from userinfo" // + " where id not in " + "(select top " // + ((pageNumber - 1) / pageSize) // + " id from userinfo order by id)" + " order by id";
// oracle写法
// String sql1 ="select / from " +
// "(select rownum r,userinfo./ from userinfo " +
// "where rownum < "+((pageNumber - 1) / pageSize + pageSize)+"t2 where t2.r >= "+((pageNumber - 1) / pageSize)+"";
if(((pageNumber - 1) /* pageSize)<0) return null;
String sql = "select /* from userinfo order by id asc limit "
+ (pageNumber - 1) /* pageSize + "," + pageSize;
ArrayList
Connection conn = null; Statement st = null; ResultSet rs = null;
try { conn = DB.getConn(); System.out.println(sql); st = conn.createStatement(); rs = st.executeQuery(sql);
while (rs.next()) { UserInfo user = new UserInfo(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); user.setAge(rs.getString("age")); UserInfoList.add(user); } } catch (SQLException e) { e.printStackTrace(); } finally { DB.closeRs(rs); DB.closeStmt(st); } return UserInfoList; }
/// / 返回总记录数 / @return // public static int getCount() { String sql = "select count(/) from userinfo"; int count = 0;
Connection conn = null; Statement st = null; ResultSet rs = null;
try { conn = DB.getConn(); st = conn.createStatement(); rs = st.executeQuery(sql);
while (rs.next()) { count = rs.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } finally { DB.closeRs(rs); DB.closeStmt(st); } System.out.println("sql记录数:"+count); return count; }
} ///////////////////////////////////////////////////////////////* 5)jsp页面 pageTest.jsp
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <%@ taglib uri="http://jsptags.com/tags/navigation/pager" prefix="pg"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"> <%@ page import="Test./"%> <%@ page import="java.util./"%> <% int total = UserDAO.getCount(); Pager pager = Pager.getInstance(request,total); String htmlcode = pager.getNavigate(); String pageNum = request.getParameter("pageNumber"); int pageNumber = 1; if (pageNum == null || pageNum=="" ) { pageNumber = 1; } else { pageNumber = Integer.parseInt(pageNum); }
ArrayList
id | name | age |
|
|
|
<%=htmlcode%>
Java学习室 — 陈伟波个人主页 E-mail: zz3zcwb@sina.com COPY RIGHT 2005