后台代码:
1.写一个实体类PageBean,存放分页的所有数据
public class PageBean<T> implements Serializable {
private static final long serialVersionUID = -3666389704889313508L;
private long total; //总数据条数
private int pagerNum; //每页展示数量
private int pages; //总页数
private int currentPage; //当前页数
List<T> t;//一页内的数据
//自己实现,中间页码数量。根据当前页数currentPage,确定bar里面的数字
private int[] bar; //存放页码的数组
public int[] getBar(){
int start;
int stop;
//默认每页显示10条
if (pages < 10){
start = 1;
stop = pages;
}else {
start = currentPage - 5;
stop = currentPage + 4;
//pages>=10页
if (currentPage - 5 <= 0){
start = 1;
stop = 10;
}
//当前页在>=6时
if (currentPage + 4 >= pages){
start = pages - 9;
stop = pages;
}
}
bar = new int[stop - start + 1];
int index = 0;
for (int i = start;i<=stop;i++){
bar[index++] = i;
}
return bar;
}
private void setBar(int[] bar){
this.bar = bar;
}
}
2.从前端a标签url跳转到servlet控制器,判断点击的种类,展示分页数据
servlet用作数据传递。
/**
* 更多热门商品
* 更多最新商品
* 种类获取商品
*/
protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = request.getParameter("param"); //区分不同操作
//种类 - 编号
String cid = request.getParameter("cid");
//页面显示数
String pagerNum = this.getServletContext().getInitParameter("pagerNum");
//页码
String currentPage = request.getParameter("currentPage");
PageBean<Product> pageBean = productService.queryProductListPage(param, cid, currentPage, pagerNum);
request.setAttribute("pageBean", pageBean);
request.setAttribute("param", param);
request.setAttribute("cid", cid);
request.getRequestDispatcher("/WEB-INF/jsp/product_list.jsp").forward(request, response);
}
3.Productservice
public class ProductServiceImpl implements ProductService {
private ProductDao productDao = new ProductDaoImpl();
@Override
public PageBean<Product> queryProductListPage(String param, String cid, String currentPage, String pagerNum) {
PageBean<Product> pageBean = new PageBean<>();
pageBean.setPagerNum(Integer.parseInt(pagerNum)); //rows查询数
int page = 1; //页码
if(currentPage != null) {
page = Integer.parseInt(currentPage);
}
pageBean.setCurrentPage(page);
int categoryId = 0;
if(cid != null) {
categoryId = Integer.parseInt(cid);
}
long total = productDao.queryProductsCount(param, categoryId);
pageBean.setTotal(total); //条数
pageBean.setPages((int)Math.ceil((double)total / pageBean.getPagerNum())); //总页码数
List<Product> products = productDao.queryProductsPage(param, categoryId, (page - 1) * pageBean.getPagerNum(), pageBean.getPagerNum());
pageBean.setList(products); //页面数据
return pageBean;
}
/**
* 商品数据 - 同步在redis缓存
*/
@Override
public Product queryProductByPid(String pid) {
Product product = null;
Jedis jedis = RedisUtils.getJedis();
String itemJSON = jedis.hget("ITEMS:ITEM", "ITEM:" + pid);
if(itemJSON == null) {
product = productDao.queryProductByPid(Integer.parseInt(pid));
//日期类型 -转JSON - 使用config
itemJSON = JSONObject.fromObject(product, JSONDateConfig.getDateJSONConfig()).toString();
jedis.hset("ITEMS:ITEM", "ITEM:" + pid, itemJSON);
} else {
product = (Product) JSONObject.toBean(JSONObject.fromObject(itemJSON), Product.class);
}
return product;
}
}
4.ProductDao
public class ProductDaoImpl implements ProductDao {
private QueryRunner queryRunner = new QueryRunner(DruidDBUtils.getDataSource());
@Override
public List<Product> queryIndexHotProducts(int rows) {
String sql = "select pid, pname, shop_price, pimages from product where is_hot = 1 and pflag = 1 order by pid desc limit ?";
try {
return queryRunner.query(sql, new BeanListHandler<>(Product.class), rows);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
@Override
public List<Product> queryIndexNewProducts(int rows) {
String sql = "select pid, pname, shop_price, pimages from product where pflag = 1 order by pid desc limit ?";
try {
return queryRunner.query(sql, new BeanListHandler<>(Product.class), rows);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
private String condition(String param, int cid) {
if("hots".equals(param)) {
return "and is_hot = 1";
} else if("news".equals(param)) {
return "";
} else if("category".equals(param)) {
return "and cid = " + cid;
}
return "";
}
@Override
public long queryProductsCount(String param, int cid) {
String sql = "select count(*) from product where pflag = 1 " + condition(param, cid);
try {
return queryRunner.query(sql, new ScalarHandler<>());
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return 0;
}
@Override
public List<Product> queryProductsPage(String param, int cid, int pageIndex, int rows) {
String sql = "select pid, pname, shop_price, pimages from product where pflag = 1 " +
condition(param, cid) +
" order by pid desc limit ?, ?";
try {
return queryRunner.query(sql, new BeanListHandler<>(Product.class), pageIndex, rows);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
@Override
public Product queryProductByPid(int pid) {
String sql = "select * from product where pid = ?";
try {
return queryRunner.query(sql, new BeanHandler<>(Product.class), pid);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
}
5.页面product_list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>极客商品- ${requestScope.param} 商品列表</title>
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/bootstrap.min.css" type="text/css" />
<script src="${pageContext.request.contextPath}/js/jquery-1.11.3.min.js" type="text/javascript"></script>
<script src="${pageContext.request.contextPath}/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>
<div class="container">
<!-- 引入header.jsp -->
<jsp:include page="header.jsp"></jsp:include>
<c:choose>
<c:when test="${empty requestScope.pageBean.list}">
<p class="text-center">暂无商品,稍后查看!</p>
</c:when>
<c:otherwise>
<div class="row">
<c:forEach var="product" items="${requestScope.pageBean.list}">
<div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;">
<a href="${pageContext.request.contextPath}/product?method=detail&pid=${product.pid}">
<img src="${pageContext.request.contextPath}/${product.pimages}" width="130" height="130" style="display: inline-block;">
</a>
<p>
<a href="${pageContext.request.contextPath}/product?method=detail&pid=${product.pid}" title="${product.pname}" style='color:#666'>
${fn:substring(product.pname, 0, 12)}
</a>
</p>
<p>
<font color="#E4393C" style="font-size:16px">
¥<fmt:formatNumber value="${product.shop_price}" minFractionDigits="2" maxFractionDigits="2"/>
</font>
</p>
</div>
</c:forEach>
</div>
<!--分页 -->
<nav aria-label="Page navigation" class="text-center">
<c:url var="url" value="${pageContext.request.contextPath}/product">
<c:param name="method" value="list"/>
<c:param name="param" value="${requestScope.param}"/>
<c:if test="${not empty requestScope.cid}">
<c:param name="cid" value="${requestScope.cid}"/>
</c:if>
</c:url>
<ul class="pagination"> <%-- page --%>
<%-- 上一页 - 控制 --%>
<c:choose>
<c:when test="${requestScope.pageBean.currentPage == 1}">
<li class="disabled">
<a href="javascript:void(0)" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:when>
<c:otherwise>
<li>
<a href="${url}¤tPage=${requestScope.pageBean.currentPage-1}" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:otherwise>
</c:choose>
<%-- 中间页码 pageBean中定义int[] bar控制中间页码 --%>
<%--<c:forEach var="page" begin="1" end="${requestScope.pageBean.pages}">--%>
<c:forEach var="page" items="${requestScope.pageBean.bar}">
<c:choose>
<c:when test="${requestScope.pageBean.currentPage == page}"> <%-- 当前页 - 激活、无点击--%>
<li class="active">
<a href="javascript:void(0)">${page}</a>
</li>
</c:when>
<c:otherwise>
<li>
<a href="${url}¤tPage=${page}">${page}</a>
</li>
</c:otherwise>
</c:choose>
</c:forEach>
<%-- 下一页 - 控制 --%>
<c:choose>
<c:when test="${requestScope.pageBean.currentPage == requestScope.pageBean.pages}">
<li class="disabled">
<a href="javascript:void(0)" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</c:when>
<c:otherwise>
<li>
<a href="${url}¤tPage=${requestScope.pageBean.currentPage+1}" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</c:otherwise>
</c:choose>
</ul>
</nav>
<!-- 分页结束 -->
</c:otherwise>
</c:choose>
<!-- 引入footer.jsp -->
<jsp:include page="footer.jsp"></jsp:include>
</div>
</body>
</html>