首页 > 代码库 > Java-分页实例

Java-分页实例

1、PageModel.java

 

package com.javaweb;import java.util.List;public class PageModel<E> {  private List<E> list; //结果集 private int totalRecords; //查询记录数 private int pageSize; //每页多少记录 private int pageNo; //当前页 //总页数 public int getTotalPages(){  return (totalRecords + pageSize - 1) / pageSize; }  //取得首页 public int getTopPageNo(){  return 1; }  //取得上一页 public int getPreviousPageNo(){  if(pageNo<=1)   return 1;  return pageNo-1; }  // 取得下一页 public int getNextPageNo(){  if(pageNo >= getBottomPageNo())   return getBottomPageNo();  return pageNo+1; }  //取得尾页 public int getBottomPageNo(){  return getTotalPages(); }  public List<E> getList() {  return list; } public void setList(List<E> list) {  this.list = list; } public int getTotalRecords() {  return totalRecords; } public void setTotalRecords(int totalRecords) {  this.totalRecords = totalRecords; } public int getPageSize() {  return pageSize; } public void setPageSize(int pageSize) {  this.pageSize = pageSize; } public int getPageNo() {  return pageNo; } public void setPageNo(int pageNo) {  this.pageNo = pageNo; }}

 

 2、Book.java

package com.javaweb.book;public class Book { private String id; private String name; private String title; private float price; private int year; private String description; private int saleAmount;  public String getId() {  return id; } public void setId(String id) {  this.id = id; } public String getName() {  return name; } public void setName(String name) {  this.name = name; } public String getTitle() {  return title; } public void setTitle(String title) {  this.title = title; } public float getPrice() {  return price; } public void setPrice(float price) {  this.price = price; } public int getYear() {  return year; } public void setYear(int year) {  this.year = year; } public String getDescription() {  return description; } public void setDescription(String description) {  this.description = description; } public int getSaleAmount() {  return saleAmount; } public void setSaleAmount(int saleAmount) {  this.saleAmount = saleAmount; }}

 3、BookDb.java

package com.javaweb.book;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.*;import com.javaweb.*;public class BookDb {  // 返回所有book public List<Book> getAllBooks(){  String sql = "select * from books order by id";  Connection conn = null;  PreparedStatement pstmt = null;  ResultSet rs = null;  List<Book> bookList = null;  try{   conn = DbUtil.getConnection();   pstmt = conn.prepareStatement(sql);   rs = pstmt.executeQuery();    bookList = new ArrayList<Book>();   while(rs.next()){    Book book = new Book();    book.setId(rs.getString("id"));    book.setName(rs.getString("name"));    book.setTitle(rs.getString("title"));    book.setPrice(rs.getFloat("price"));    book.setYear(rs.getInt("yr"));    book.setDescription(rs.getString("description"));    book.setSaleAmount(rs.getInt("sale_amount"));    bookList.add(book);   }  }catch(SQLException e){   e.printStackTrace();  }finally{   DbUtil.close(rs);   DbUtil.close(pstmt);   DbUtil.close(conn);  }  return bookList; }  //返回id查询book //@param id book的id public Book getBookById(String id){  String sql = "select * from books where id=?";  Connection conn = null;  PreparedStatement pstmt = null;  ResultSet rs = null;  Book book = null;  try{   conn = DbUtil.getConnection();   pstmt = conn.prepareStatement(sql);   pstmt.setString(1, id);   rs = pstmt.executeQuery();   while(rs.next()){    book = new Book();    book.setId(rs.getString("id"));    book.setName(rs.getString("name"));    book.setTitle(rs.getString("title"));    book.setPrice(rs.getFloat("price"));    book.setYear(rs.getInt("yr"));    book.setDescription(rs.getString("description"));    book.setSaleAmount(rs.getInt("sale_amount"));   }  }catch(SQLException e){   e.printStackTrace();  }finally{   DbUtil.close(rs);   DbUtil.close(pstmt);   DbUtil.close(conn);  }  return book; }  //分页查询(上一页、下一页) //@param pageNo 第几页 //@param pageSize 每页多少记录 public PageModel<Book> findBookList(int pageNo,int pageSize){  String sql = "select * from books order by id limit ?,?";  Connection conn = null;  PreparedStatement pstmt = null;  ResultSet rs = null;  PageModel<Book> pageModel = null;  try{   conn = DbUtil.getConnection();   pstmt = conn.prepareStatement(sql);   pstmt.setInt(1, (pageNo-1)*pageSize);   pstmt.setInt(2, pageSize);   rs = pstmt.executeQuery();   List<Book> bookList = new ArrayList<Book>();   while(rs.next()){    Book book = new Book();    book.setId(rs.getString("id"));    book.setName(rs.getString("name"));    book.setTitle(rs.getString("title"));    book.setPrice(rs.getFloat("price"));    book.setYear(rs.getInt("yr"));    book.setDescription(rs.getString("description"));    book.setSaleAmount(rs.getInt("sale_amount"));    bookList.add(book);   }   pageModel = new PageModel<Book>();   pageModel.setList(bookList);   pageModel.setPageNo(pageNo);   pageModel.setPageSize(pageSize);   pageModel.setTotalRecords(getTotalRecords(conn));  }catch(SQLException e){   e.printStackTrace();  }finally{   DbUtil.close(rs);   DbUtil.close(pstmt);   DbUtil.close(conn);  }  return pageModel; }   //取得总记录数 private int getTotalRecords(Connection conn) throws SQLException{  String sql = "select count(*) from books";  PreparedStatement pstmt = null;  ResultSet rs = null;  int count = 0;  try{   pstmt = conn.prepareStatement(sql);   rs = pstmt.executeQuery();   rs.next();   count = rs.getInt(1);  }finally{   DbUtil.close(rs);   DbUtil.close(pstmt);  }  return count; }}

 4、DbUtil.java

package com.javaweb.book;import java.sql.*;public class DbUtil { private final static String driver = "com.mysql.jdbc.Driver"; private final static String url = "jdbc:mysql://localhost:3306/bookdb"; private final static String user = "root"; private final static String password = "123456";  public static Connection getConnection(){  try{   Class.forName(driver);   Connection conn = DriverManager.getConnection(url,user,password);   return conn;  }catch(ClassNotFoundException e){   System.out.println("找不到数据库驱动");   System.out.println(e.getMessage());  }catch(SQLException e){   System.out.println("数据库连接失败");   System.out.println(e.getMessage());  }  return null; }  public static void close(Connection conn){  if(conn!=null){   try{    conn.close();   }catch(SQLException e){    System.out.println("关闭数据库连接出错");    System.out.println(e.getMessage());   }  } }  public static void close(ResultSet rs){  if(rs!=null){   try{    rs.close();   }catch(SQLException e){    e.printStackTrace();   }  } }  public static void close(PreparedStatement pstmt){  if(pstmt!=null){   try{    pstmt.close();   }catch(SQLException e){    e.printStackTrace();   }  } }}

 5、bookstore.jsp

<%@ page contentType="text/html;charset=GBK" %><html><head><title>Bookstore</title></head><body><center><p><b><a href="http://blog.163.com/jesse_zy/blog/<%=request.getContextPath()%>/catalog.jsp">查看所有书目</a></b></center></body></html>  6、catalog.jsp<%@ page language="java" import="java.util.*" pageEncoding="GBK"%><%@ page import="java.util.*" %><%@ page import="com.javaweb.*" %><%@ page import="com.javaweb.book.*" %><% int pageNo = 1; int pageSize = 4; String pageNoString = request.getParameter("pageNo"); if(pageNoString != null){  pageNo = Integer.parseInt(pageNoString); } PageModel<Book> pageModel = new BookDb().findBookList(pageNo,pageSize);%><html>  <head>    <title>图书详细信息</title>    <link rel="stylesheet" href="http://blog.163.com/jesse_zy/blog/style.css">  </head>   <script type="text/javascript">     function topPage() {  window.self.location = "catalog.jsp?pageNo=<%=pageModel.getTopPageNo()%>"; }  function previousPage() {  window.self.location = "catalog.jsp?pageNo=<%=pageModel.getPreviousPageNo()%>"; }   function nextPage() {  window.self.location = "catalog.jsp?pageNo=<%=pageModel.getNextPageNo()%>"; }  function bottomPage() {  window.self.location = "catalog.jsp?pageNo=<%=pageModel.getBottomPageNo()%>"; }  </script>   <body>  <div align="center">    <form>      <table width="900" height="30" border="0" cellspacing="0">        <tr>          <td>图书列表</td>          <td align="right"><a href="http://blog.163.com/jesse_zy/blog/bookstore.jsp">返回主页</a></td>        </tr>      </table>      <table  width="900" border="1" cellspacing="0" cellpadding="0">        <tr>          <th>ID</th>          <th>作者</th>          <th>书名</th>          <th>价格</th>          <th>出版年份</th>          <th>描述</th>          <th>销量</th>        </tr>        <%         List<Book> bookList = pageModel.getList();         for(Book book:bookList){        %>        <tr>          <td><%= book.getId()%></td>          <td><%= book.getName()%></td>          <td><%= book.getTitle()%></td>          <td><%= book.getPrice()%></td>          <td><%= book.getYear()%></td>          <td><%= book.getDescription()%></td>          <td><%= book.getSaleAmount()%></td>        </tr>        <%         }        %>      </table>      <table width="900" height="35" border="0" cellspacing="0">       <tr>         <td>          <div>     共 <%=pageModel.getTotalPages() %> 页</font>        当前第 <font color="red"><%=pageModel.getPageNo() %></font> 页   </div>         </td>         <td>   <div align="right">    <input type="button" value="http://www.mamicode.com/首页" onClick="topPage()"    <% if(pageNo<=1) {    %>disabled="disabled"    <% }%>>    <input type="button" value="http://www.mamicode.com/上一页" onClick="previousPage()"    <% if(pageNo<=1) {    %>disabled="disabled"    <% }%>>    <input type="button" value="http://www.mamicode.com/下一页" onClick="nextPage()"    <% if(pageNo>=pageModel.getBottomPageNo()) {    %>disabled="disabled"    <% }%>>    <input type="button" value="http://www.mamicode.com/尾页" onClick="bottomPage()"    <% if(pageNo>=pageModel.getBottomPageNo()) {    %>disabled="disabled"    <% }%>>    </div>    </td>       <tr>      </table>    </form>    </div>  </body></html>

 7、style.css

th{ font-family : 宋体; font-size : 12pt;}td{ font-family : 宋体; font-size : 11pt;}

 8、books.sql

drop database BookDB;create database BookDB;use BookDB;create table BOOKS(ID varchar(8) primary key,NAME varchar(24),TITLE varchar(96),PRICE float,YR int,DESCRIPTION varchar(128),SALE_AMOUNT int);insert into BOOKS values(‘001‘,‘李建‘,‘Java面向对象编程‘,65,2006, ‘让读者由浅入深掌握Java语言‘, 20000);insert into BOOKS values(‘001‘,‘李建‘,‘Java面向对象编程‘,65,2006, ‘让读者由浅入深掌握Java语言‘, 20000);insert into BOOKS values(‘002‘, ‘李建‘, ‘精通Struts‘, 49, 2004, ‘真的很棒‘, 80000);insert into BOOKS values(‘003‘, ‘李建‘, ‘Tomcat与JavaWeb开发技术详解‘, 45, 2004, ‘关于Tomcat与JavaWeb开发的技术书‘, 40000);insert into BOOKS values(‘004‘, ‘李建‘, ‘Java网络编程精解‘,55, 2007, ‘很值得一看‘, 20000);insert into BOOKS values(‘005‘, ‘李建‘, ‘精通Hibernate‘, 59, 2005, ‘权威的Hibernate技术资料‘, 50000);insert into BOOKS values(‘006‘, ‘李建‘, ‘Java2认证考试指南与试题解析‘, 88, 2002, ‘权威的Java技术资料‘, 8000);

 

Java-分页实例