JavaWeb后端入门12—分页

1. 核心点

1.1 如何封装一个PageBean对象

完成分页功能至少需要以下5个数据

  • 1.每一页的商品列表
    • 实现:使用select * from 表查询,封装数据至List<Product>
  • 2.总页数
    • 实现:总商品数 ÷ 每页显示的商品个数,向上取整
  • 3.当前页数
    • 实现:前台传递数据
  • 4.每页显示的商品个数
    • 实现:自行定义
  • 5.总商品数
    • 实现 select count(*) from product需强转类型(详见9)

1.2 SQL的查询语句

  • 查询总商品数count(*)
代码语言:javascript代码运行次数:0运行复制
String sql = "select count(*) from product";
Long count = (Long)queryRunner.query(sql, new ScalarHandler());
return count.intValue();

先将Object转换为Long,再转换为int

  • 分页查询limit ?,?
代码语言:javascript代码运行次数:0运行复制
select * from product limit ?,?

第一个参数为查询开始的位置,第二个参数为单次查询多少个

2. 后台代码

2.1 PageBean(可以放在domain,也可以放在vo)

代码语言:javascript代码运行次数:0运行复制
package cn.wuter.vo;

import java.util.ArrayList;
import java.util.List;

import cn.wuter.domain.Product;

public class PageBean<T> {
	//当前页的数据
	private List<T> productList = new ArrayList<T>();
	//总页数
	private int totalPage;
	//当前页数
	private int currentPage;
	//数据总个数
	private int totalCount;
	//当前页显示的条数
	private int currentCount;
	

	public List<T> getProductList() {
		return productList;
	}
	public void setProductList(List<T> productList) {
		this.productList = productList;
	}
	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;
	}
	public int getTotalCount() {
		return totalCount;
	}
	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}
	public int getCurrentCount() {
		return currentCount;
	}
	public void setCurrentCount(int currentCount) {
		this.currentCount = currentCount;
	}
	
}

2.2 Servlet

代码语言:javascript代码运行次数:0运行复制
package cn.wuter.web;
/**
 * 显示商品列表的Servlet
 * */
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.wuter.domain.Product;
import cn.wuter.service.ProductService;
import cn.wuter.vo.PageBean;

public class ProductListServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.1获取当前页,如果没有当前页赋值为1
		String currentPageStr = request.getParameter("currentPage");
		if (currentPageStr == null) {
			currentPageStr = "1";
		}
		int currentPage = Integer.parseInt(currentPageStr) ;
		//1.2默认每页显示12条
		int currentCount = 12;
		
		//2.传递请求到Service层
		ProductService service =  new ProductService();
		PageBean<Product> pageBean = null;
		try {
			pageBean = service.findPageBean(currentPage,currentCount);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		//3.数据库查询数据结果传递给jsp
		request.setAttribute("pageBean", pageBean);
		request.getRequestDispatcher("./product_list.jsp").forward(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

2.3 Service层

代码语言:javascript代码运行次数:0运行复制
package cn.wuter.service;

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

import cn.wuter.dao.ProductDao;
import cn.wuter.domain.Product;
import cn.wuter.vo.PageBean;

public class ProductService {
	/**
	 * 分页操作
	 * @throws SQLException 
	 * */
	public PageBean findPageBean(int currentPage,int currentCount) throws SQLException {
		
		ProductDao dao = new ProductDao();
		
		// 封装PageBean并返回
		PageBean pageBean = new PageBean();
		//1.封装当前页currentPage
		pageBean.setCurrentPage(currentPage);
		//2.封装当前页显示的条数currentCount
		pageBean.setCurrentCount(currentCount);
		//3.封装总条数totalCount
		int totalCount =  dao.getTotalCount();
		pageBean.setTotalCount(totalCount);
		//4.封装总页数totalPage
		int totalPage = (int) Math.ceil(1.0*totalCount/currentCount);
		pageBean.setTotalPage(totalPage);
		//5.每页显示的数据List<T> productList
		int index = (currentPage - 1 ) * currentCount;
		List<Product> productList = dao.findProductListForPageBean(index,currentCount);
		pageBean.setProductList(productList);
		return pageBean;
	}

}

2.4 Dao层

代码语言:javascript代码运行次数:0运行复制
package cn.wuter.dao;

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

import javax.security.auth.message.callback.PrivateKeyCallback.Request;
import javax.servlet.http.HttpServletRequest;

import org.apachemons.dbutils.DbUtils;
import org.apachemons.dbutils.QueryRunner;
import org.apachemons.dbutils.handlers.BeanHandler;
import org.apachemons.dbutils.handlers.BeanListHandler;
import org.apachemons.dbutils.handlers.ScalarHandler;

import cn.wuter.domain.Product;
import cn.wuter.utils.JDBCUtils;
import cn.wuter.web.ProductInfoServlet;

public class ProductDao {
	/**
	 * 获得全部商品的条数
	 * @throws SQLException 
	 * */
	public int getTotalCount() throws SQLException {
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		String sql = "select count(*) from product";
		Long count = (Long)queryRunner.query(sql, new ScalarHandler());
		return count.intValue();
	}
	/**
	 * 获得分页的商品数据
	 * @throws SQLException 
	 * */
	public List<Product> findProductListForPageBean(int index, int currentCount) throws SQLException {
		QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
		String sql = "select * from product limit ?,?";
		List<Product> productList = queryRunner.query(sql, new BeanListHandler<Product>(Product.class),index,currentCount);
		return productList;
	}

}

3. 前台代码

代码语言:javascript代码运行次数:0运行复制
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
	<%@taglib uri="; prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>商品列表</title>
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
<script src="js/jquery-1.11.3.min.js" type="text/javascript"></script>
<script src="js/bootstrap.min.js" type="text/javascript"></script>
<!-- 引入自定义css文件 style.css -->
<link rel="stylesheet" href="css/style.css" type="text/css" />

<style>
body {
	margin-top: 20px;
	margin: 0 auto;
	width: 100%;
}

.carousel-inner .item img {
	width: 100%;
	height: 300px;
}
</style>
</head>

<body>

<c:if test="${ empty pageBean.productList }">
<%response.sendRedirect("./ProductListServlet"); %>
</c:if>

	<div class="row" style="width: 1210px; margin: 0 auto;">
		<div class="col-md-12">
			<ol class="breadcrumb">
				<li><a href="#">这是从数据库实时获取的商品信息</a></li>
			</ol>
		</div>
		<c:forEach items="${pageBean.productList }" var="product" >
			<div class="col-md-2">
				<a href="ProductInfoServlet?product_id=${ product.pid}"> 
					<img src="${pageContext.request.contextPath }/${product.pimage }" width="170" height="170" style="display: inline-block;">
				</a>
				<p>
					<a href="ProductInfoServlet?product_id=${ product.pid}" style='color: green'>${product.pname }</a>
				</p>
				<p>
					<p class="clear">商城价:¥<s>${product.market_price }</s> </p>
					<c:if test="${product.is_hot == 1 }"><img alt="hot" src="products/hot.png" style="height: 30px"></c:if>
					<span style="color: red;font-size: 20px;float: right;">${product.shop_price }</span> 
					
				</p>
			</div>
		</c:forEach>		
	</div>

	<!--分页 -->
	<div style="width: 380px; margin: 0 auto; margin-top: 50px;">
		<ul class="pagination" style="text-align: center; margin-top: 10px;">
			<!-- 上一页 -->
			<c:if test="${pageBean.currentPage==1 }">
				<li class="disabled"><a href="javascript:;" aria-label="Previous"><span aria-hidden="true">«</span></a></li>
			</c:if>
			<c:if test="${pageBean.currentPage!=1 }">
				<li class=""><a href="./ProductListServlet?currentPage=${pageBean.currentPage-1 }" aria-label="Previous"><span aria-hidden="true">«</span></a></li>
			</c:if>
			<!-- 获取总页数并分页 -->
			<c:forEach begin="1" end="${pageBean.totalPage }" var="page" >
				<c:if test="${pageBean.currentPage==page }">
					<li class="active"><a href="javascript:;">${page }</a></li>
				</c:if>
				<c:if test="${pageBean.currentPage!=page }">
					<li><a href="./ProductListServlet?currentPage=${page }">${page }</a></li>	
				</c:if>
			</c:forEach>
			<!-- 下一页 -->
			<c:if test="${pageBean.currentPage==pageBean.totalPage }">
				<li class="disabled"><a href="javascript:;" aria-label="Next"><span aria-hidden="true">»</span></a></li>
			</c:if>
			<c:if test="${pageBean.currentPage!=pageBean.totalPage }">
				<li class=""><a href="./ProductListServlet?currentPage=${pageBean.currentPage+1 }" aria-label="Next"><span aria-hidden="true">»</span></a></li>
			</c:if>
		</ul>
	</div>
	<!-- 分页结束 -->

	<!--商品浏览记录-->
	<div
		style="width: 1210px; margin: 0 auto; padding: 0 9px; border: 1px solid #ddd; border-top: 2px solid #999; height: 246px;">

		<h4 style="width: 50%; float: left; font: 14px/30px 微软雅黑">浏览记录</h4>
		<div style="width: 50%; float: right; text-align: right;">
			<a href="">more</a>
		</div>
		<div style="clear: both;"></div>

		<div style="overflow: hidden;">

			<ul style="list-style: none;">
				<li
					style="width: 150px; height: 216; float: left; margin: 0 8px 0 0; padding: 0 18px 15px; text-align: center;"><img
					src="products/1/cs10001.jpg" width="130px" height="130px" /></li>
			</ul>

		</div>
	</div>
</body>

</html>

4. 易错点

1. 总商品数的查询需要强转类型

2. 两个int相除向上取整需要给int乘以1.0先转换为double

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。 原始发表:2021-05-07 ,如有侵权请联系 cloudcommunity@tencent 删除入门数据import分页后端