jsp实现分页(限定显示指定页数)和页面跳转功能

来源:互联网 发布:软件著作权 发表状态 编辑:程序博客网 时间:2024/05/22 04:44

      本文主要介绍在jsp中实现分页功能和页面跳转功能,能够实现数据的分页显示和跳转到指定页面的功能,具体效果如图

                       

由于该功能是一个书城项目的一部分,所以数据来源于该项目,具体数据库(数据库方面采用c3p0连接池,使用的是MySQL数据库)文件可以在点击打开链接下载,整个项目可以在点击打开链接下载(不过由于使用的是MyeElipse2013,所以请使用此版本或者更高版本导入工程)。

下面具体介绍一下这个小功能

1. 这个项目的目录结构:

2.显示的数据主要是图书的相关信息因此Bean类是图书Book的相关信息即com.page.book.domain中Book类的相关信息如下

[java] view plain copy
print?
  1. package com.page.book.domain;  
  2.   
  3. import org.apache.log4j.Category;  
  4.   
  5. public class Book {  
  6.     private String bid;//主键  
  7.     private String bname;//图名  
  8.     private String author;//作者  
  9.     private double price;//定价  
  10.     private double currPrice;//当前价  
  11.     private double discount;//折扣  
  12.     private String press;//出版社  
  13.     private String publishtime;//出版时间  
  14.     private int edition;//版次  
  15.     private int pageNum;//页数  
  16.     private int wordNum;//字数  
  17.     private String printtime;//刷新时间  
  18.     private int booksize;//开本  
  19.     private String paper;//纸质  
  20.     private Category category;//所属分类  
  21.     private String image_w;//大图路径  
  22.     private String image_b;//小图路径  
  23.     public String getBid() {  
  24.         return bid;  
  25.     }  
  26.     public void setBid(String bid) {  
  27.         this.bid = bid;  
  28.     }  
  29.     public String getBname() {  
  30.         return bname;  
  31.     }  
  32.     public void setBname(String bname) {  
  33.         this.bname = bname;  
  34.     }  
  35.     public String getAuthor() {  
  36.         return author;  
  37.     }  
  38.     public void setAuthor(String author) {  
  39.         this.author = author;  
  40.     }  
  41.     public double getPrice() {  
  42.         return price;  
  43.     }  
  44.     public void setPrice(double price) {  
  45.         this.price = price;  
  46.     }  
  47.     public double getCurrPrice() {  
  48.         return currPrice;  
  49.     }  
  50.     public void setCurrPrice(double currPrice) {  
  51.         this.currPrice = currPrice;  
  52.     }  
  53.     public double getDiscount() {  
  54.         return discount;  
  55.     }  
  56.     public void setDiscount(double discount) {  
  57.         this.discount = discount;  
  58.     }  
  59.     public String getPress() {  
  60.         return press;  
  61.     }  
  62.     public void setPress(String press) {  
  63.         this.press = press;  
  64.     }  
  65.     public String getPublishtime() {  
  66.         return publishtime;  
  67.     }  
  68.     public void setPublishtime(String publishtime) {  
  69.         this.publishtime = publishtime;  
  70.     }  
  71.     public int getEdition() {  
  72.         return edition;  
  73.     }  
  74.     public void setEdition(int edition) {  
  75.         this.edition = edition;  
  76.     }  
  77.     public int getPageNum() {  
  78.         return pageNum;  
  79.     }  
  80.     public void setPageNum(int pageNum) {  
  81.         this.pageNum = pageNum;  
  82.     }  
  83.     public int getWordNum() {  
  84.         return wordNum;  
  85.     }  
  86.     public void setWordNum(int wordNum) {  
  87.         this.wordNum = wordNum;  
  88.     }  
  89.     public String getPrinttime() {  
  90.         return printtime;  
  91.     }  
  92.     public void setPrinttime(String printtime) {  
  93.         this.printtime = printtime;  
  94.     }  
  95.     public int getBooksize() {  
  96.         return booksize;  
  97.     }  
  98.     public void setBooksize(int booksize) {  
  99.         this.booksize = booksize;  
  100.     }  
  101.     public String getPaper() {  
  102.         return paper;  
  103.     }  
  104.     public void setPaper(String paper) {  
  105.         this.paper = paper;  
  106.     }  
  107.     public Category getCategory() {  
  108.         return category;  
  109.     }  
  110.     public void setCategory(Category category) {  
  111.         this.category = category;  
  112.     }  
  113.     public String getImage_w() {  
  114.         return image_w;  
  115.     }  
  116.     public void setImage_w(String image_w) {  
  117.         this.image_w = image_w;  
  118.     }  
  119.     public String getImage_b() {  
  120.         return image_b;  
  121.     }  
  122.     public void setImage_b(String image_b) {  
  123.         this.image_b = image_b;  
  124.     }  
  125. }  
3.dao层的实现

[java] view plain copy
print?
  1. package com.page.book.dao;  
  2.   
  3. import java.sql.SQLException;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6.   
  7. import org.apache.commons.dbutils.QueryRunner;  
  8. import org.apache.commons.dbutils.handlers.BeanListHandler;  
  9. import org.apache.commons.dbutils.handlers.ScalarHandler;  
  10.   
  11. import cn.itcast.jdbc.TxQueryRunner;  
  12.   
  13. import com.page.book.domain.Book;  
  14. import com.page.pager.Expression;  
  15. import com.page.pager.PageBean;  
  16. import com.page.pager.PageConstants;  
  17.   
  18. public class BookDao {  
  19.     private QueryRunner qr = new TxQueryRunner();  
  20.       
  21.     /** 
  22.      * 按分类查询 
  23.      * @param cid 
  24.      * @param pc 
  25.      * @return 
  26.      * @throws SQLException  
  27.      */  
  28.     public PageBean<Book> findByCategory(String cid, int pc) throws SQLException {  
  29.         List<Expression> exprList = new ArrayList<Expression>();  
  30.         exprList.add(new Expression("cid""=", cid));  
  31.         return findByCriteria(exprList, pc);  
  32.     }  
  33.       
  34.   
  35.   
  36.       
  37.     /** 
  38.      * 通用的查询方法 
  39.      * @param exprList 
  40.      * @param pc 
  41.      * @return 
  42.      * @throws SQLException  
  43.      */  
  44.     private PageBean<Book> findByCriteria(List<Expression> exprList, int pc) throws SQLException {  
  45.         /* 
  46.          * 1. 得到ps 
  47.          * 2. 得到tr 
  48.          * 3. 得到beanList 
  49.          * 4. 创建PageBean,返回 
  50.          */  
  51.         /* 
  52.          * 1. 得到ps 
  53.          */  
  54.         int ps = PageConstants.BOOK_PAGE_SIZE;//每页记录数  
  55.         /* 
  56.          * 2. 通过exprList来生成where子句 
  57.          */  
  58.         StringBuilder whereSql = new StringBuilder(" where 1=1");   
  59.         List<Object> params = new ArrayList<Object>();//SQL中有问号,它是对应问号的值  
  60.         for(Expression expr : exprList) {  
  61.             /* 
  62.              * 添加一个条件上, 
  63.              * 1) 以and开头 
  64.              * 2) 条件的名称 
  65.              * 3) 条件的运算符,可以是=、!=、>、< ... is null,is null没有值 
  66.              * 4) 如果条件不是is null,再追加问号,然后再向params中添加一与问号对应的值 
  67.              */  
  68.             whereSql.append(" and ").append(expr.getName())  
  69.                 .append(" ").append(expr.getOperator()).append(" ");  
  70.             // where 1=1 and bid = ?  
  71.             if(!expr.getOperator().equals("is null")) {  
  72.                 whereSql.append("?");  
  73.                 params.add(expr.getValue());  
  74.             }  
  75.         }  
  76.   
  77.         /* 
  78.          * 3. 总记录数  
  79.          */  
  80.         String sql = "select count(*) from t_book" + whereSql;  
  81.         Number number = (Number)qr.query(sql, new ScalarHandler(), params.toArray());  
  82.         int tr = number.intValue();//得到了总记录数  
  83.         /* 
  84.          * 4. 得到beanList,即当前页记录 
  85.          */  
  86.         sql = "select * from t_book" + whereSql + " order by orderBy limit ?,?";  
  87.         params.add((pc-1) * ps);//当前页首行记录的下标  
  88.         params.add(ps);//一共查询几行,就是每页记录数  
  89.           
  90.         List<Book> beanList = qr.query(sql, new BeanListHandler<Book>(Book.class),   
  91.                 params.toArray());  
  92.           
  93.         /* 
  94.          * 5. 创建PageBean,设置参数 
  95.          */  
  96.         PageBean<Book> pb = new PageBean<Book>();  
  97.         /* 
  98.          * 其中PageBean没有url,这个任务由Servlet完成 
  99.          */  
  100.         pb.setBeanList(beanList);  
  101.         pb.setPc(pc);  
  102.         pb.setPs(ps);  
  103.         pb.setTr(tr);  
  104.           
  105.         return pb;  
  106.     }  
  107.       
  108.       
  109. }  
4.service层的实现

[java] view plain copy
print?
  1. package com.page.book.service;  
  2.   
  3. import java.sql.SQLException;  
  4.   
  5. import com.page.book.dao.BookDao;  
  6. import com.page.book.domain.Book;  
  7. import com.page.pager.PageBean;  
  8.   
  9. public class BookService {  
  10.     private BookDao bookDao = new BookDao();  
  11.       
  12.     /** 
  13.      * 按分类查 
  14.      * @param cid 
  15.      * @param pc 
  16.      * @return 
  17.      */  
  18.     public PageBean<Book> findByCategory(String cid, int pc) {  
  19.         try {  
  20.             return bookDao.findByCategory(cid, pc);  
  21.         } catch (SQLException e) {  
  22.             throw new RuntimeException(e);  
  23.         }  
  24.     }  
  25.       
  26. }  
5.servlet的实现

[java] view plain copy
print?
  1. package com.page.book.servlet;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import javax.servlet.ServletException;  
  6. import javax.servlet.http.HttpServletRequest;  
  7. import javax.servlet.http.HttpServletResponse;  
  8.   
  9. import cn.itcast.servlet.BaseServlet;  
  10.   
  11. import com.page.book.domain.Book;  
  12. import com.page.book.service.BookService;  
  13. import com.page.pager.PageBean;  
  14.   
  15. public class BookServlet extends BaseServlet {  
  16.     /** 
  17.      *  
  18.      */  
  19.     private static final long serialVersionUID = 1L;  
  20.     private BookService bookService = new BookService();  
  21.       
  22.     /** 
  23.      * 获取当前页码 
  24.      * @param req 
  25.      * @return 
  26.      */  
  27.     private int getPc(HttpServletRequest req) {  
  28.         int pc = 1;  
  29.         String param = req.getParameter("pc");  
  30.         if(param != null && !param.trim().isEmpty()) {  
  31.             try {  
  32.                 pc = Integer.parseInt(param);  
  33.             } catch(RuntimeException e) {}  
  34.         }  
  35.         return pc;  
  36.     }  
  37.       
  38.     /** 
  39.      * 截取url,页面中的分页导航中需要使用它做为超链接的目标! 
  40.      * @param req 
  41.      * @return 
  42.      */  
  43.     /* 
  44.      * http://localhost:8080/goods/BookServlet?methed=findByCategory&cid=xxx&pc=3 
  45.      * /goods/BookServlet + methed=findByCategory&cid=xxx&pc=3 
  46.      */  
  47.     private String getUrl(HttpServletRequest req) {  
  48.           
  49.         String url = req.getRequestURI() + "?" + req.getQueryString();  
  50.         System.out.println("url:"+url);  
  51.         /* 
  52.          * 如果url中存在pc参数,截取掉,如果不存在那就不用截取。 
  53.          */  
  54.         int index = url.lastIndexOf("&pc=");  
  55.         if(index != -1) {  
  56.             url = url.substring(0, index);  
  57.         }  
  58.         return url;  
  59.     }  
  60.       
  61.     public String findByCategory(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {  
  62.         /* 
  63.          * 1. 得到pc:如果页面传递,使用页面的,如果没传,pc=1 
  64.          */  
  65.         int pc = getPc(req);  
  66.         /* 
  67.          * 2. 得到url:... 
  68.          */  
  69.         String url = getUrl(req);  
  70.         System.out.println("url----"+url);  
  71.         /* 
  72.          * 3. 获取查询条件,本方法就是cid,即分类的id 
  73.          */  
  74.         String cid = req.getParameter("cid");  
  75.         /* 
  76.          * 4. 使用pc和cid调用service#findByCategory得到PageBean 
  77.          */  
  78.         PageBean<Book> pb = bookService.findByCategory(cid, pc);  
  79.         /* 
  80.          * 5. 给PageBean设置url,保存PageBean,转发到/jsps/book/list.jsp 
  81.          */  
  82.         pb.setUrl(url);  
  83.         req.setAttribute("pb", pb);  
  84.         return "f:/pager/pager.jsp";//f代表转发  
  85.     }  
  86. }  
6.关于分页的相关类的实现

[java] view plain copy
print?
  1. package com.page.pager;  
  2.   
  3. public class PageConstants {  
  4.     public static final int BOOK_PAGE_SIZE = 12;//图书每页记录数  
  5. }  
7.pageBean的实现

[java] view plain copy
print?
  1. package com.page.pager;  
  2.   
  3. import java.util.List;  
  4.   
  5. /** 
  6.  * 分页Bean,它会在各层之间传递 
  7.  * 
  8.  * @param <T> 
  9.  */  
  10. public class PageBean<T> {  
  11.     private int pc;//当前页码  
  12.     private int tr;//总记录数  
  13.     private int ps;//每页记录数  
  14.     private String url;//请求路径和参数,例如BookServlet?method=findXXX&cid=1&bname=2  
  15.     private List<T> beanList;  
  16.       
  17.     // 计算总页数  
  18.     public int getTp() {  
  19.         int tp = tr / ps;  
  20.         return tr % ps == 0 ? tp : tp + 1;  
  21.     }  
  22.       
  23.     public int getPc() {  
  24.         return pc;  
  25.     }  
  26.     public void setPc(int pc) {  
  27.         this.pc = pc;  
  28.     }  
  29.     public int getTr() {  
  30.         return tr;  
  31.     }  
  32.     public void setTr(int tr) {  
  33.         this.tr = tr;  
  34.     }  
  35.     public int getPs() {  
  36.         return ps;  
  37.     }  
  38.     public void setPs(int ps) {  
  39.         this.ps = ps;  
  40.     }  
  41.     public String getUrl() {  
  42.         return url;  
  43.     }  
  44.     public void setUrl(String url) {  
  45.         this.url = url;  
  46.     }  
  47.     public List<T> getBeanList() {  
  48.         return beanList;  
  49.     }  
  50.     public void setBeanList(List<T> beanList) {  
  51.         this.beanList = beanList;  
  52.     }  
  53. }  
8.数据库辅助类

[java] view plain copy
print?
  1. package com.page.pager;  
  2.   
  3. public class Expression {  
  4.     private String name;  
  5.     private String operator;  
  6.     private String value;  
  7.     public String getName() {  
  8.         return name;  
  9.     }  
  10.     public void setName(String name) {  
  11.         this.name = name;  
  12.     }  
  13.     public String getOperator() {  
  14.         return operator;  
  15.     }  
  16.     public void setOperator(String operator) {  
  17.         this.operator = operator;  
  18.     }  
  19.     public String getValue() {  
  20.         return value;  
  21.     }  
  22.     public void setValue(String value) {  
  23.         this.value = value;  
  24.     }  
  25.     @Override  
  26.     public String toString() {  
  27.         return "Expression [name=" + name + ", operator=" + operator  
  28.                 + ", value=" + value + "]";  
  29.     }  
  30.     public Expression() {  
  31.         super();  
  32.         // TODO Auto-generated constructor stub  
  33.     }  
  34.     public Expression(String name, String operator, String value) {  
  35.         super();  
  36.         this.name = name;  
  37.         this.operator = operator;  
  38.         this.value = value;  
  39.         toString();  
  40.     }  
  41.       
  42.       
  43. }  
9.c3p0文件的配置

[html] view plain copy
print?
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <c3p0-config>  
  3.     <default-config>   
  4.         <property name="jdbcUrl">  
  5.             <![CDATA[ 
  6.                 jdbc:mysql://localhost:3306/goods?useUnicode=true&characterEncoding=UTF8&useServerPrepStmts=true&prepStmtCacheSqlLimit=256&cachePrepStmts=true&prepStmtCacheSize=256&rewriteBatchedStatements=true 
  7.             ]]>  
  8.         </property>  
  9.         <property name="driverClass">com.mysql.jdbc.Driver</property>  
  10.         <property name="user">root</property>  
  11.         <property name="password">906363842aq</property>  
  12.           
  13.         <property name="acquireIncrement">3</property>  
  14.         <property name="initialPoolSize">10</property>  
  15.         <property name="minPoolSize">2</property>  
  16.         <property name="maxPoolSize">10</property>  
  17.     </default-config>  
  18. </c3p0-config>  
10.分页前端的操作

[html] view plain copy
print?
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
  3.     <link rel="stylesheet" type="text/css" href="<c:url value='/pager/pager.css'/>" />  
  4.         <script type="text/javascript" src="<c:url value='/pager/jquery-1.5.1.js'/>"></script>  
  5. <script type="text/javascript">  
  6.     function _go() {  
  7.         var pc = $("#pageCode").val();//获取文本框中的当前页码  
  8.         if(!/^[1-9]\d*$/.test(pc)) {//对当前页码进行整数校验  
  9.             alert('请输入正确的页码!');  
  10.             return;  
  11.         }  
  12.         if(pc > ${pb.tp}) {//判断当前页码是否大于最大页  
  13.             alert('请输入正确的页码!');  
  14.             return;  
  15.         }  
  16.         location = "${pb.url}&pc=" + pc;  
  17.     }  
  18. </script>  
  19. <table border="1">  
  20.  <tr>  
  21.   <th>书名</th>  
  22.   <th>书价</th>  
  23.   <th>折扣</th>  
  24.   <th>作者</th>  
  25.   <th>出版社</th>  
  26.   <th>出版时间</th>  
  27.   </tr>  
  28.   <c:forEach items="${pb.beanList }" var="book">  
  29.    
  30.   <tr>  
  31.     <td>${book.bname }</td>  
  32.     <td>${book.price }</td>  
  33.     <td>${book.discount }折</td>  
  34.     <td>${book.author }</td>  
  35.     <td>${book.press }</td>  
  36.     <td>${book.publishtime }</td>  
  37.   </tr>  
  38.   </c:forEach>  
  39. </table>  
  40.   
  41.   
  42. <div class="divBody">  
  43.   <div class="divContent">  
  44.     <%--上一页 --%>  
  45. <c:choose>  
  46.     <c:when test="${pb.pc eq 1 }"><span class="spanBtnDisabled">上一页</span></c:when>  
  47.     <c:otherwise><a href="${pb.url }&pc=${pb.pc-1}" class="aBtn bold">上一页</a></c:otherwise>  
  48. </c:choose>  
  49.           
  50.           
  51.   
  52. <%--我们需要计算页码列表的开始和结束位置,即两个变量begin和end  
  53. 计算它们需要通过当前页码!  
  54. 1. 总页数不足6页--> begin=1end=最大页  
  55. 2. 通过公式设置begin和end,begin=当前页-1,end=当前页+3  
  56. 3. 如果begin<1,那么让begin=1end=6  
  57. 4. 如果end>tp, 让begin=tp-5, end=tp  
  58.  --%>  
  59.  <c:choose>  
  60.     <c:when test="${pb.tp <= 6 }">  
  61.         <c:set var="begin" value="1"/>  
  62.         <c:set var="end" value="${pb.tp }"/>  
  63.     </c:when>  
  64.     <c:otherwise>  
  65.         <c:set var="begin" value="${pb.pc-2 }"/>  
  66.         <c:set var="end" value="${pb.pc + 3}"/>  
  67.         <c:if test="${begin < 1 }">  
  68.           <c:set var="begin" value="1"/>  
  69.           <c:set var="end" value="6"/>  
  70.         </c:if>  
  71.         <c:if test="${end > pb.tp }">  
  72.           <c:set var="begin" value="${pb.tp-5 }"/>  
  73.           <c:set var="end" value="${pb.tp }"/>  
  74.         </c:if>         
  75.     </c:otherwise>  
  76.  </c:choose>  
  77.    
  78.  <c:forEach begin="${begin }" end="${end }" var="i">  
  79.    <c:choose>  
  80.       <c:when test="${i eq pb.pc }">  
  81.         <span class="spanBtnSelect">${i }</span>  
  82.       </c:when>  
  83.       <c:otherwise>  
  84.         <a href="${pb.url }&pc=${i}" class="aBtn">${i }</a>  
  85.       </c:otherwise>  
  86.    </c:choose>  
  87.              
  88.               
  89.  </c:forEach>  
  90.     <%-- 计算begin和end --%>  
  91.       <%-- 如果总页数<=6,那么显示所有页码,即begin=1 end=${pb.tp} --%>  
  92.         <%-- 设置begin=当前页码-2,end=当前页码+3 --%>  
  93.           <%-- 如果begin<1,那么让begin=1 end=6 --%>  
  94.           <%-- 如果end>最大页,那么begin=最大页-5 end=最大页 --%>  
  95.   
  96.   
  97.       
  98.     <%-- 显示点点点 --%>  
  99.     <c:if test="${end < pb.tp }">  
  100.       <span class="spanApostrophe">...</span>  
  101.     </c:if>   
  102.   
  103.       
  104.      <%--下一页 --%>  
  105. <c:choose>  
  106.     <c:when test="${pb.pc eq pb.tp }"><span class="spanBtnDisabled">下一页</span></c:when>  
  107.     <c:otherwise><a href="${pb.url }&pc=${pb.pc+1}" class="aBtn bold">下一页</a></c:otherwise>  
  108. </c:choose>  
  109.           
  110.           
  111.             
  112.       
  113.     <%-- 共N页 到M页 --%>  
  114.     <span>共${pb.tp }页</span>  
  115.     <span></span>  
  116.     <input type="text" class="inputPageCode" id="pageCode" value="${pb.pc }"/>  
  117.     <span></span>  
  118.     <a href="javascript:_go();" class="aSubmit">确定</a>  
  119.   </div>  
  120. </div>  
本文转自:http://blog.csdn.net/it_tingge/article/details/48896983

阅读全文
1 0