欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

【Java】 Java分页功能实现,

来源: javaer 分享于  点击 46108 次 点评:17

【Java】 Java分页功能实现,


实现步骤:

**
**

product模型类定义如下(根据自己的数据库而定)

**

package cn.jishupeng.bookstore.model;

public class Product {
    private String id;
    private String name;
    private double price;
    private String category;
    private int pnum;
    private String imgurl;
    private String description;

    public Product() {
    }

    public Product(String id, String name, double price, String category, int pnum, String imgurl, String description) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.category = category;
        this.pnum = pnum;
        this.imgurl = imgurl;
        this.description = description;
    }

    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 double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public int getPnum() {
        return pnum;
    }

    public void setPnum(int pnum) {
        this.pnum = pnum;
    }

    public String getImgurl() {
        return imgurl;
    }

    public void setImgurl(String imgurl) {
        this.imgurl = imgurl;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "Product{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", category='" + category + '\'' +
                ", pnum=" + pnum +
                ", imgurl='" + imgurl + '\'' +
                ", description='" + description + '\'' +
                '}';
    }
}

1 定义一个pageResult模型用于存储分页相关信息, 实现代码如下:

**

package cn.jishupeng.bookstore.model;

import java.util.List;

public class PageResult<T> {
    List<T> list;
    long totalCount;
    int pageSize = 4;
    int totalPage;
    int currentPage;

    public PageResult() {
    }

    public PageResult(List<T> list, long totalCount, int pageSize, int totalPage, int currentPage) {
        this.list = list;
        this.totalCount = totalCount;
        this.pageSize = pageSize;
        this.totalPage = totalPage;
        this.currentPage = currentPage;
    }

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

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

    public long getTotalCount() {
        return totalCount;
    }

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

    public int getPageSize() {
        return pageSize;
    }

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

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    @Override
    public String toString() {
        return "PageResult{" +
                "totalCount=" + totalCount +
                ", pageSize=" + pageSize +
                ", totalPage=" + totalPage +
                ", currentPage=" + currentPage +
                '}';
    }
}

**

2. 创建一个IProductDao接口和ProductImpl实现类, 编写dao层代码:

**

dao/IProductDao.interface

package cn.jishupeng.bookstore.dao;

import cn.jishupeng.bookstore.model.Product;

import java.sql.SQLException;
import java.util.List;

public interface IProductDao {
    /*
    * 根据商品分类查询商品总数量
    * */
    public abstract long count(String category) throws SQLException;


    /*
    * 通过分类和页码数查找对应分类的商品详细信息, 将数据封装进一个列表并返回
    * */
    public abstract List<Product> findProductByCategoryAndCurrentPage(String category, int currentPage, int pageSize) throws SQLException;
}

/dao/ProductDaoImpl

package cn.jishupeng.bookstore.dao.daoImpl;

import cn.jishupeng.bookstore.dao.IProductDao;
import cn.jishupeng.bookstore.model.Product;
import cn.jishupeng.bookstore.utils.C3P0Util;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ProductDaoImpl implements IProductDao {
    @Override
    public long count(String category) throws SQLException {
        /*
        * 定义一个初始化count变量
        * */
        long count=0;

        QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
        String sql = "select count(*) from products where 1=1";

        /*
        * 判断: 当参数category部位空对象, 并且不为空字符串, 才将category作为查询条件
        * */
        if (category != null && !"".equals(category)) {
            sql += " and category = ?";
            count = (long)qr.query(sql, new ScalarHandler(), category);
        } else {
            /*
            * 否则就查询所有商品总数, new ScalarHandler()返回的是一个但行单列的数据, 类型为Object
            * */
            count = (long)qr.query(sql, new ScalarHandler());
        }

        return count;
    }

    @Override
    public List<Product> findProductByCategoryAndCurrentPage(String category, int currentPage, int pageSize) throws SQLException {
        QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
        /*
        * 技巧: 定义一个列表对象用于存储查询参数, 执行query查询的时候可以直接传入列表
        * */
        List<Object> list = new ArrayList<>();

        String sql = "select * from products where 1=1";

        if (category != null && !"".equals(category)) {
            sql += " and category=?";
            /*
            * 当category有效, 则把参数放入列表中
            * */
            list.add(category);
        }

        /*
        * 定义跳过数据条数skip和每次显示数据长度length
        * */
        int skip = (currentPage - 1) * pageSize;
        int length = pageSize;
        list.add(skip);
        list.add(length);

        sql += " limit ?,?";

        return qr.query(sql, new BeanListHandler<Product>(Product.class), list.toArray());
    }

    public static void main(String[] args) throws SQLException {
        IProductDao pDao = new ProductDaoImpl();
        long count = pDao.count(null);
        List<Product> products = pDao.findProductByCategoryAndCurrentPage(null, 1, 4);

        System.out.println(count);
        for (Product product : products) {
            System.out.println(product);
        }
    }
}

**

3. 编写service代码

**

IProductService

package cn.jishupeng.bookstore.service;

import cn.jishupeng.bookstore.model.ModifyUser;
import cn.jishupeng.bookstore.model.PageResult;
import cn.jishupeng.bookstore.model.Product;
import cn.jishupeng.bookstore.model.User;

public interface IProductService {


    /*
     * 根据分类和当前页查找商品数据,
     * 此方法需要将查询到的数据封装到PageResult<Product>中, 并且返回给前台
     * */
    public abstract PageResult<Product> findProductByCategoryAndCurrentPage(String category, int currentPage, int pageSize) throws Exception;
}

/service/ProductServiceImpl

package cn.jishupeng.bookstore.service.UserServiceImpl;

import cn.jishupeng.bookstore.dao.IProductDao;
import cn.jishupeng.bookstore.dao.daoImpl.ProductDaoImpl;
import cn.jishupeng.bookstore.model.PageResult;
import cn.jishupeng.bookstore.model.Product;
import cn.jishupeng.bookstore.service.IProductService;

import java.sql.SQLException;
import java.util.List;

public class ProductServiceImpl implements IProductService {
    IProductDao proDao = new ProductDaoImpl();

    @Override
    public PageResult<Product> findProductByCategoryAndCurrentPage(String category, int currentPage, int pageSize) throws SQLException {
        /*
         * 实例化PageResult模型
         * */
        PageResult<Product> pr = new PageResult<>();

        /*
         * 获取并设置总商品数量
         * */
        long totalCount = proDao.count(category);
        pr.setTotalCount(totalCount);

        /*
         * 获取并设置每页显示的数量
         * */
        pr.setCurrentPage(currentPage);

        /*
         * 计算并设置总页数totalPage
         * */
        int totalPage = (int)(totalCount % pr.getPageSize() == 0 ? totalCount / pr.getPageSize() : (totalCount / pr.getPageSize()) + 1);
        pr.setTotalPage(totalPage);

        /*
         * 执行查询并设置 list
         * */
        List<Product> list = proDao.findProductByCategoryAndCurrentPage(category, currentPage, pageSize);
        pr.setList(list);

        /*
         * 返回pageResult对象
         * */
        return pr;
    }
}

**

4. servlet代码实现

**

package cn.jishupeng.bookstore.web.servlet;

import cn.jishupeng.bookstore.model.PageResult;
import cn.jishupeng.bookstore.model.Product;
import cn.jishupeng.bookstore.service.IProductService;
import cn.jishupeng.bookstore.service.UserServiceImpl.ProductServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/showProductByPage")
public class ShowProductByPageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        IProductService productService = new ProductServiceImpl();
        String category = req.getParameter("category");
        String currentPage = req.getParameter("page");
        int page = 1;
        try {
            if (currentPage != null && !currentPage.equals("")) {
                 page = Integer.parseInt(currentPage);
            }
            PageResult<Product> pageResult = productService.findProductByCategoryAndCurrentPage(category, page, 4);
            req.setAttribute("pageResult", pageResult);
            req.setAttribute("category", category);
            req.getRequestDispatcher("/product_list.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

**

6.jsp页面功能

**

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>


<title>bookStore列表</title>
<%--导入css --%>
<link rel="stylesheet" href="css/main.css" type="text/css" />
</head>

<body class="main">

	<jsp:include page="head.jsp" />
	<jsp:include page="menu_search.jsp" />

	<div id="divpagecontent">
		<table width="100%" border="0" cellspacing="0">
			<tr>

				<td>
					<div >
						<a href="index.jsp">首页</a>&nbsp;&nbsp;&nbsp;&nbsp;&gt;&nbsp;&nbsp;&nbsp;&nbsp;计算机&nbsp;&nbsp;&nbsp;&nbsp;&gt;&nbsp;&nbsp;&nbsp;&nbsp;图书列表
					</div>

					<table cellspacing="0" class="listcontent">
						<tr>
							<td>
								<h1>商品目录</h1>
								<hr />
								<h1>计算机</h1>&nbsp;&nbsp;&nbsp;&nbsp;共${pageResult.totalCount}种商品
								<hr />
								<div >
									<img src="images/productlist.gif" width="100%" height="38" />
								</div>
								<table cellspacing="0" class="booklist">
									<tr>
										<c:forEach items="${pageResult.list}" var="product">

										<td>
											<div class="divbookpic">
												<p>
													<a href="product_info.jsp"><img src="bookcover/101.jpg" width="115"
														height="129" border="0" /> </a>
												</p>
											</div>

											<div class="divlisttitle">
												<a href="product_info.jsp">书名:${product.name}<br />售价: ${product.price}</a>
											</div></td>
										</c:forEach>

										<%--<td>

											<div class="divbookpic">
												<p>
													<a href="product_info.jsp"><img src="bookcover/102.jpg" width="115"
														height="129" border="0" /> </a>
												</p>
											</div>

											<div class="divlisttitle">
												<a href="product_info.jsp">书名:xxx<br />售价:xxx </a>
											</div></td>
										<td>

											<div class="divbookpic">
												<p>
													<a href="product_info.jsp"><img src="bookcover/103.jpg" width="115"
														height="129" border="0" /> </a>
												</p>
											</div>

											<div class="divlisttitle">
												<a href="product_info.jsp">书名:xxx<br />售价:xxx </a>
											</div></td>
										<td>

											<div class="divbookpic">
												<p>
													<a href="product_info.jsp"><img src="bookcover/104.jpg" width="115"
														height="129" border="0" /> </a>
												</p>
											</div>

											<div class="divlisttitle">
												<a href="product_info.jsp">书名:xxx<br />售价:xxx </a>
											</div></td>--%>


									</tr>
								</table>

								<%--<table cellspacing="0" class="booklist">
									<tr>
										<td>

											<div class="divbookpic">
												<p>
													<a href="product_info.jsp"><img src="bookcover/101.jpg" width="115"
														height="129" border="0" /> </a>
												</p>
											</div>

											<div class="divlisttitle">
												<a href="product_info.jsp">书名:xxx<br />售价:xxx </a>
											</div></td>
										<td>

											<div class="divbookpic">
												<p>
													<a href="product_info.jsp"><img src="bookcover/102.jpg" width="115"
														height="129" border="0" /> </a>
												</p>
											</div>

											<div class="divlisttitle">
												<a href="product_info.jsp">书名:xxx<br />售价:xxx </a>
											</div></td>
										<td>

											<div class="divbookpic">
												<p>
													<a href="product_info.jsp"><img src="bookcover/103.jpg" width="115"
														height="129" border="0" /> </a>
												</p>
											</div>

											<div class="divlisttitle">
												<a href="product_info.jsp">书名:xxx<br />售价:xxx </a>
											</div></td>
										<td>

											<div class="divbookpic">
												<p>
													<a href="product_info.jsp"><img src="bookcover/104.jpg" width="115"
														height="129" border="0" /> </a>
												</p>
											</div>

											<div class="divlisttitle">
												<a href="product_info.jsp">书名:xxx<br />售价:xxx </a>
											</div></td>


									</tr>
								</table>--%>















								<div class="pagination">
									第${pageResult.currentPage}页&nbsp;/&nbsp;共${pageResult.totalPage}页
									<ul>

										<c:if test="${pageResult.currentPage == 1}">
											<li class="disablepage"><a href="${pageContext.request.contextPath}/showProductByPage?category=${category}&page=1">上一页&gt;&gt;</a></li>
										</c:if>

										<c:if test="${pageResult.currentPage != 1}">
											<li class="disablepage"><a href="${pageContext.request.contextPath}/showProductByPage?category=${category}&page=${pageResult.currentPage - 1}">上一页&gt;&gt;</a></li>
										</c:if>

										<%--<li class="currentpage">1</li>--%>
										<c:forEach begin="1" end="${pageResult.totalPage}" var="i">
											<li><a href="${pageContext.request.contextPath}/showProductByPage?category=${category}&page=${i}">${i}</a>
											</li>
										</c:forEach>




										<c:if test="${pageResult.currentPage == pageResult.totalPage}">
											<li class="nextpage"><a href="${pageContext.request.contextPath}/showProductByPage?category=${category}&page=${pageResult.totalPage}">下一页&gt;&gt;</a>
											</li>
										</c:if>

										<c:if test="${pageResult.currentPage != pageResult.totalPage}">
										<li class="nextpage"><a href="${pageContext.request.contextPath}/showProductByPage?category=${category}&page=${pageResult.currentPage + 1}">下一页&gt;&gt;</a>
										</c:if>

									</ul>
								</div>
							</td>
						</tr>
					</table></td>
			</tr>
		</table>
	</div>



	<jsp:include page="foot.jsp" />


</body>
</html>

相关文章

    暂无相关文章
相关栏目:

用户点评