Shop项目--4. 分页显示商品的,与分页跳转,上一页,下一页product_list.jsp

分析:

1.分页显示商品,需要pageBean对象, 里面维护着 currentPage,currentCount,totalPage,totalCount List<?>

List<Product>装的是根据cid查询到的商品列表,在后台封装好pageBean对象,就能在前台编辑分页显示。

2.分页显示,显示其实就是执行一个功能取到该页的pageBean对象,该功能需要获取当前页currentPage,与cid参数。注意传递

3.每个分页显示的商品是有限的,所以dao层查询的商品列表要有开始索引index与每页显示的数量currentPage。

4.上一页,下一页,还有其他页跳转,需要判断是否为当前页


准备:

pageBean类


步骤:

从head.jsp 进入content+="<li><a href='${pageContext.request.contextPath}/product?method=productListByCid&cid="+data[i].cid+"'>"+data[i].cname+"</a></li>"

1.在web层获取cid,currentPage(如为空,设置为1)与设置currentCount并传递到service层。

2.在service层封装pageBean  

1)currentPage 

2)currentCount 

3)totalCount(根据cid传递到dao层查找)

4)totalPage(总页数除以当前页)

5)List<product>(根据cid index 还有显示数量传递到dao层获取)

3.web层 把pageBean cid 传到request域并转发到 product_list.jsp页面


在product_list.jsp前端页面 

4.根据pageBean.totalPage 遍历显示所有的分页page

5.判断当前页currentPage是否为page,如是则不能跳转,设置为javascript: 如不是则可以跳转携带cid currentPage 执行分页显示功能

6.同理判断当前页是否为第一页或最后一页,携带cid currentPage 执行分页功能


header.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<!-- 登录 注册 购物车... -->
<div class="container-fluid">
	<div class="col-md-4">
		<img src="img/logo2.png" />
	</div>
	<div class="col-md-5">
		<img src="img/header.png" />
	</div>
	<div class="col-md-3" style="padding-top:20px">
		<ol class="list-inline">
			<li><a href="login.jsp">登录</a></li>
			<li><a href="register.jsp">注册</a></li>
			<li><a href="cart.jsp">购物车</a></li>
			<li><a href="order_list.jsp">我的订单</a></li>
		</ol>
	</div>
</div>

<!-- 导航条 -->
<div class="container-fluid">
	<nav class="navbar navbar-inverse">
		<div class="container-fluid">
			<!-- Brand and toggle get grouped for better mobile display -->
			<div class="navbar-header">
				<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
					<span class="sr-only">Toggle navigation</span>
					<span class="icon-bar"></span>
					<span class="icon-bar"></span>
					<span class="icon-bar"></span>
				</button>
				<a class="navbar-brand" href="#">首页</a>
			</div>
			
			<!-- 商品分类列表 ajax-->
			<script type="text/javascript">
				$(function(){
					$.post(
							"${pageContext.request.contextPath}/product?method=category",
							function(data){
								//[{"cid":"xxx","cname":"xxx"},{},{},{},{}]
								var content ="";
								for (var i = 0; i < data.length; i++) {
									//拼接字符串后,内部双引号必须改为单引号
									//a标签链接为根据cid查找商品的一个servlet,注意拼接字符串
									content+="<li><a href='${pageContext.request.contextPath}/product?method=productListByCid&cid="+data[i].cid+"'>"+data[i].cname+"</a></li>"
								}
								//添加li到ul中
								$("#categoryUl").html(content);
							},
							"json"
						);
				});
			</script>
			<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
				<ul class="nav navbar-nav" id="categoryUl">
					<!-- <li class="active"><a href="product_list.htm">手机数码<span class="sr-only">(current)</span></a></li>
					<li><a href="#">电脑办公</a></li>
					<li><a href="#">电脑办公</a></li>
					<li><a href="#">电脑办公</a></li>
 -->				</ul>
				<form class="navbar-form navbar-right" role="search">
					<div class="form-group">
						<input type="text" class="form-control" placeholder="Search">
					</div>
					<button type="submit" class="btn btn-default">Submit</button>
				</form>
			</div>
		</div>
	</nav>
</div>

ProductServlet

package com.itheima.web.servlet;

import java.io.IOException;
import java.util.List;

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

import com.google.gson.Gson;
import com.itheima.domain.Category;
import com.itheima.domain.PageBean;
import com.itheima.domain.Product;
import com.itheima.service.ProductService;
import com.itheima.utils.JedisPoolUtils;

import redis.clients.jedis.Jedis;

public class ProductServlet extends BaseServlet {

	//根据商品分类的cid获取商品,分页显示功能
	public void productListByCid(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		//获取商品分类的cid
		String cid = request.getParameter("cid");
		//获取当前页,如果没有当前页,设置为第一页
		String currentPageStr = request.getParameter("currentPage");
		if(currentPageStr==null) {
			currentPageStr ="1";
		}
		//当前页,与当前显示数
		int currentPage = Integer.parseInt(currentPageStr);
		int currentCount =12;
		//传递到service层,pageBean
		ProductService service = new ProductService();
		PageBean<Product>  pageBean =  service.findPageBeanByCid(cid,currentPage,currentCount);
		//传递pageBean 与 cid 等待分页下一次执行该功能时候使用
		request.setAttribute("cid", cid);
		request.setAttribute("pageBean", pageBean);
		request.getRequestDispatcher("/product_list.jsp").forward(request, response);
	}
	
	//获取商品的分类列表
	public void category(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		
		ProductService service = new ProductService();
		//先从缓存中查询是否有categoryList,没有再从数据库中查询
		//1.获得jedis对象连接redis数据库
		Jedis jedis = JedisPoolUtils.getJedis();
		String categoryListJson = jedis.get("categoryListJson");
		//2.判断categoryList是否为空
		if(categoryListJson==null) {
			System.out.println("缓存没有数据,查找数据库");
			//准备分类数据
			List<Category> categoryList = service.findCategory();
			Gson gson = new Gson();
			categoryListJson = gson.toJson(categoryList);
			jedis.set("categoryListJson", categoryListJson);
		}
		//有中文,所以要解决乱码问题
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().write(categoryListJson);
	}
	
	//首页动态获取最新商品和热门商品
	public void index(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		ProductService service = new ProductService();
		//获取热门商品
		List<Product> hotProList = service.findHotProduct();
		//获取最新商品
		List<Product> newProList = service.findNewProduct();
		//传递到request域,并转发到index.jsp
		request.setAttribute("hotProList", hotProList);
		request.setAttribute("newProList", newProList);
		request.getRequestDispatcher("/index.jsp").forward(request, response);
		
	}
	
}

ProductService

package com.itheima.service;

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

import com.itheima.dao.ProductDao;
import com.itheima.domain.Category;
import com.itheima.domain.PageBean;
import com.itheima.domain.Product;

public class ProductService {

	//获取热门商品
	public List<Product> findHotProduct() {
		ProductDao dao = new ProductDao();
		List<Product> hotProList = null;
		try {
			hotProList = dao.findHotProduct();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return hotProList;
	}

	//获取最新商品
	public List<Product> findNewProduct() {
		ProductDao dao = new ProductDao();
		List<Product> newProList = null;
		try {
			newProList = dao.findNewProduct();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return newProList;
	}

	//获取商品列表
	public List<Category> findCategory() {
		ProductDao dao = new ProductDao();
		List<Category> categoryList = null;
		try {
			categoryList = dao.findCategory();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return categoryList;
	}

	//根据cid获取pagebean
	public PageBean findPageBeanByCid(String cid, int currentPage, int currentCount) {
		ProductDao dao = new ProductDao();
		PageBean<Product> pageBean = new PageBean<Product>();
		//当前页
		pageBean.setCurrentPage(currentPage);
		//当前页显示条数
		pageBean.setCurrentCount(currentCount);
		//总共条数
		int totalCount = 0;
		try {
			totalCount = dao.findtotalCount(cid);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		pageBean.setTotalCount(totalCount);
		//总共页数
		// math.ceil向上取整 该方法内的是double类型 所以乘以1.0
		int totalPage = (int) Math.ceil(1.0*totalCount/currentCount);
		pageBean.setTotalPage(totalPage);
		//商品列表,计算从多少角标开始取
		int index = (currentPage-1)*currentCount;
		List<Product> productList = null;
		try {
			productList = dao.findProductListByCid(cid,index,currentCount);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		pageBean.setList(productList);
		return pageBean;
	}


}

ProductDao

package com.itheima.dao;


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


import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;


import com.itheima.domain.Category;
import com.itheima.domain.Product;
import com.itheima.utils.DataSourceUtils;


public class ProductDao {


	// 获取热门商品
	public List<Product> findHotProduct() throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "select * from product where is_hot=? limit ?,?";
		List<Product> query = runner.query(sql, new BeanListHandler<Product>(Product.class), 1,0,9);
		return query;
	}


	//获取最新商品
	public List<Product> findNewProduct() throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		//此处注意使用order by pdate desc 时间最大开始选择
		String sql ="select * from product order by pdate desc limit ?,?";
		List<Product> query = runner.query(sql, new BeanListHandler<Product>(Product.class), 0,9);
		return query;
	}


	//获取商品分类列表
	public List<Category> findCategory() throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql ="select * from category";
		List<Category> query = runner.query(sql, new BeanListHandler<Category>(Category.class));
		return query;
	}


	// 根据商品分类的cid获取商品
	public List<Product> findProductListByCid(String cid, int index, int currentPage) throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "select * from product where cid=? limit ?,?";
		List<Product> query = runner.query(sql, new BeanListHandler<Product>(Product.class), cid,index,currentPage);
		return query;
	}


	//根据cid查找商品总条数
	public int findtotalCount(String cid) throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql ="select count(*) from product where cid=?";
		Long query = (Long) runner.query(sql, new ScalarHandler(), cid);
		//Long转为int
		return query.intValue();
	}


	//根据pid查找商品
	public Product findProductByPid(String pid) throws SQLException {
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "select * from product where pid=?";
		Product query = runner.query(sql, new BeanHandler<Product>(Product.class), pid);
		return query;
	}


}

product_list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" 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>


	<!-- 引入header.jsp -->
	<jsp:include page="/header.jsp"></jsp:include>


	<div class="row" style="width: 1210px; margin: 0 auto;">
		<div class="col-md-12">
			<ol class="breadcrumb">
				<li><a href="#">首页</a></li>
			</ol>
		</div>
		
		<!-- 根据cid分类的商品列表 -->
		<c:forEach items="${pageBean.list }" var="product">
			<div class="col-md-2" style="height: 250px">
				<a href="product_info.htm"> <img src="${product.pimage }"
					width="170" height="170" style="display: inline-block;">
				</a>
				<p>
					<a href="product_info.html" style='color: green'>${product.pname }</a>
				</p>
				<p>
					<font color="#FF0000">商城价:¥${product.shop_price }</font>
				</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">
				 	<!-- 不能点击的设置 javascript:void(0);-->
				 	<a href="javascript:void(0);" aria-label="Previous">
				 		<span aria-hidden="true">«</span>
				 	</a>
				 </li>
			</c:if>
			<c:if test="${pageBean.currentPage!=1}">
				 <li >
				 	<a href="${pageContext.request.contextPath }/product?method=productListByCid&cid=${cid}¤tPage=${pageBean.currentPage-1}" aria-label="Previous">
				 		<span aria-hidden="true">«</span>
				 	</a>
				 </li>
			</c:if>
			
			<!-- 分页显示代码 -->
			<!-- 1.遍历,显示所有分页 -->
			<c:forEach begin="1" end="${pageBean.totalPage }" var="page">
				<!--2.判断是否当前页  -->
				<c:if test="${pageBean.currentPage==page }">
					<li class="active"><a href="#">${page }</a></li>
				</c:if>
				<c:if test="${pageBean.currentPage!=page }">
					<!--3. 跳转到另外一页,需要携带cid与page  -->
					<li><a href="${pageContext.request.contextPath}/product?method=productListByCid&cid=${cid}¤tPage=${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>
					<a href="${pageContext.request.contextPath }/product?method=productListByCid&cid=${cid}¤tPage=${pageBean.currentPage+1}" aria-label="Next">
						<span aria-hidden="true">»</span>
					</a>
				</li>
			</c:if>
			
			<!-- <li class="disabled"><a href="#" aria-label="Previous"><span
					aria-hidden="true">«</span></a></li>
			<li class="active"><a href="#">1</a></li>
			<li><a href="#">2</a></li>
			<li><a href="#">3</a></li>
			<li><a href="#">4</a></li>
			<li><a href="#">5</a></li>
			<li><a href="#">6</a></li>
			<li><a href="#">7</a></li>
			<li><a href="#">8</a></li>
			<li><a href="#">9</a></li>
			<li><a href="#" aria-label="Next"> <span aria-hidden="true">»</span>
			</a></li> -->
		</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>


	<!-- 引入footer.jsp -->
	<jsp:include page="/footer.jsp"></jsp:include>

</body>

</html>




  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值