>>分享Java Web开发技术,并且对孙卫琴的《Tomcat与Java Web开发技术详解》提供技术支持 书籍支持  卫琴直播  品书摘要  在线测试  资源下载  联系我们
发表一个新主题 开启一个新投票 回复文章 您是本文章第 23631 个阅读者 刷新本主题
 * 贴子主题:  JavaWeb分页的简单实现 回复文章 点赞(0)  收藏  
作者:sunshine    发表时间:2018-06-15 07:27:12     消息  查看  搜索  好友  邮件  复制  引用

1. 首先是创建分页所需要的通用的javabean类,其封装了分页显示页面所需要的5项数据(见下面代码注释)。我这里命名为PageBean.java,其代码如下:

import java.io.Serializable;
import java.util.List;

@SuppressWarnings("serial")
public class PageBean<E> implements Serializable{

    private List<E> list;     // 某对象(比如说商城商品)当前页的数据
    private Integer currPage; // 当前所在的页数,如第1页,第2页
    private Integer pageSize; // 每页所包含的商品的数量
    @SuppressWarnings("unused")
    private Integer totalPage;  // 总页数
    private Integer totalCount; // 总商品数

    public List<E> getList() {
        return list;
    }

    public void setList(List<E> list) {
        this.list = list;
    }

    public Integer getCurrPage() {
        return currPage;
    }

    public void setCurrPage(Integer currPage) {
        this.currPage = currPage;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Integer getTotalPage() {
        return  (int) Math.ceil(totalCount * 1.0 / pageSize);
    }

    public Integer getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(Integer totalCount) {
        this.totalCount = totalCount;
    }

    public PageBean() {
        super();
    }

    public PageBean(List<E> list, Integer currPage, Integer pageSize, Integer totalCount) {
        super();
        this.list = list;
        this.currPage = currPage;
        this.pageSize = pageSize;
        this.totalCount = totalCount;
    }
}
2. 控制层Servlet类PageServlet.java代码

public class PageServlet extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        //req.setCharacterEncoding("utf-8");
        //res.setContentType("text/html;charset=utf-8");
        
        String currPage = req.getParameter("currPage");
        // 当前页变量
        Integer iCurrPage = null;
        if (currPage != null) {
            iCurrPage = Integer.parseInt(currPage);
        } else {
            iCurrPage = 1;  // 没有指定显示哪页时,默认显示第1页
        }
        String category = req.getParameter("category");  // 根据商品类别查询,如果为null则查询全部书籍
        
        ProductService bookService = new ProductService();
        
        PageBean<Product> pb = bookService.findPageBean(iCurrPage, category);
        
        // 将封装好的pb转发到显示页面:"product_list.jsp"
        req.getSession().setAttribute("pb", pb);
        res.sendRedirect(req.getContextPath() + "/product_list.jsp");

    }

    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        doGet(req, res);
    }
}
3. service层封装此PageBean的代码

public class ProductService {

    public PageBean<Product> findPageBean(Integer iCurrPage, String category) {
        // 每页显示4本书
        int pageSize = 4;
        // 创建一个新的PageBean对象pb
        PageBean<Product> pb = new PageBean<Product>();
        // 封装当前页数到pb对象
        pb.setCurrPage(iCurrPage);
         // 封装每页显示商品数到pb对象
        pb.setPageSize(pageSize);

        ProductDao productDao = new ProductDao();
        // totalCount: 数据库中商品的总数
        Integer totalCount = null;
        List<Product> currPageBookList = null;
        try {
            totalCount = productDao.findTotalCount();
            currPageBookList = productDao.findBooksByPage(iCurrPage, pageSize, category);
        } catch (SQLException e) {
            e.printStackTrace();
        }
         // 封装商品总数数据到pb
        pb.setTotalCount(totalCount);
         // 封装当前页商品List列表数据到pb
        pb.setList(currPageBookList);
        // 返回此pb给Servlet
        return pb;
    }
}
4. Dao层去数据库查询相PageBean所需要的数据

public class ProductDao {

    public Integer findTotalCount() throws SQLException {
        QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select count(*) from product";
        return ((Long)qr.query(sql, new ScalarHandler())).intValue();
    }

    public List<Product> findBooksByPage(Integer iCurrPage, int pageSize, String category) throws SQLException {
        QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
        String sql = null;
        if (category != null) {  // 查询指定类别的商品
            sql = "select * from product where category=? limit ?,?";
            return qr.query(sql, new BeanListHandler<Product>(Product.class), category, (iCurrPage-1)*pageSize, pageSize);
        } else { // 查询所有类别的商品
            sql = "select * from product limit ?,?";
            return qr.query(sql, new BeanListHandler<Product>(Product.class), (iCurrPage-1)*pageSize, pageSize);
        }
    }
}
5. 最后在前端product_list.jsp页面进行分页显示

<table cellspacing="0" class="booklist">
    <tr>
        <c:forEach items="${pb.list}" var="book">
            <td>
                <div class="divbookpic">
                    <p>
                        <a href="product_info.jsp"><img src="${pageContext.request.contextPath}/${book.imgurl}" width="115"
                            height="129" border="0" alt="${book.name}"/>
                        </a>
                    </p>
                </div>
                <div class="divlisttitle">
                    <a href="product_info.jsp">书名:${book.name}<br />售价:${book.price}</a>
                </div>
            </td>
        </c:forEach>
    </tr>
</table>

<!-- 分页导航 -->
<div class="pagination">
    <ul>
        <c:if test="${pb.currPage==1}">
            <li class="disablepage"><a href="javascript:void(0);"><<上一页</a></li>
        </c:if>
        <c:if test="${pb.currPage!=1}">
            <li><a href="${pageContext.request.contextPath}/pageServlet?currPage=${pb.currPage-1}"><<上一页</a></li>
        </c:if>
        
        <!-- <li>第${pb.currPage}页/共${pb.totalPage}页</li> -->
        <c:forEach begin="1" end="${pb.totalPage}" var="v">
            <li><a href="product_info.jsp">${v}</a></li>
        </c:forEach>
        
        
        <c:if test="${pb.currPage==pb.totalPage}">
            <li class="disablepage"><a href="javascript:void(0);">下一页>></a></li>
        </c:if>
        <c:if test="${pb.currPage!=pb.totalPage}">
            <li ><a href="${pageContext.request.contextPath}/pageServlet?currPage=${pb.currPage+1}">下一页>></a></li>
        </c:if>
    </ul>
</div>

原文出处:https://segmentfault.com/a/1190000012495633


程序猿的技术大观园:www.javathinker.net
  Java面向对象编程-->Java语言中的修饰符
  JavaWeb开发-->访问数据库(Ⅰ)
  JSP与Hibernate开发-->映射组成关系
  Java网络编程-->创建非阻塞的HTTP服务器
  精通Spring-->虚拟DOM和render()函数
  Vue3开发-->绑定CSS样式
  从HttpServletRequest对象中获取各种路径信息
  HTTP请求方式:GET 对比 POST
  JSP 发送邮件
  JSP 自动刷新
  Servlet 网页重定向
  详解在Linux系统中安装Tomcat
  在JSP中如何取得form表单中被选中的radio项的值
  详解如何给Tomcat配置Https/ssl证书
  30分钟学会使用Spring Web Services基础开发
  好消息《Tomcat与JavaWeb开发技术详解》第3版出版,业界大咖...
  网页上实现分享到微信和QQ等的源代码
  [讨论]请问有没有会Html 5 工程师
  JSP 到数据库查询的数据 分页显示
  JSP中访问JavaBean
  Servlet 4的核心技术
  更多...
 IPIP: 已设置保密
树形列表:   
1页 1条记录 当前第1
发表一个新主题 开启一个新投票 回复文章


中文版权所有: JavaThinker技术网站 Copyright 2016-2026 沪ICP备16029593号-2
荟萃Java程序员智慧的结晶,分享交流Java前沿技术。  联系我们
如有技术文章涉及侵权,请与本站管理员联系。