Shop项目--6. 商品的浏览历史记录。product.list.jsp

来源:互联网 发布:阿里云redis 编辑:程序博客网 时间:2024/06/05 04:00

分析:

1.商品浏览历史记录,使用cookies技术来完成,把商品的pid存到cookies中保存。

2.每次访问商品详情页面时候,可以在代码加上功能模块,提取客户端cookies(习惯判断cookies不为空),获取需要cookies中名为pids的信息,并编辑pid,pid上限,顺序。

3.第一次访问的时候,cookies中的pids信息为空。把pid赋值给pids

4.把pids存到cookie,给客户端

5.有了这pids,页面就能根据pids中每一个pid查找浏览过的商品,显示到页面上。


准备:


步骤:

在方法productInfo中继续完善代码。

1.获取cookies,并判断是否为空,如不为空,遍历cookies,寻找名为pids的cookie、cookie.getName(),并获取该cookie的值value

2.获取该值value后为 3-2-1 形式的字符串 。把它用“-”切割变成数组,并把数组变成集合。

3.创建linkedList,并把该集合放进去进行创建。(为了增删操作方便,所以使用linkedList)。

4.判断该集合中是否有当前商品的pid,如果有把该集合中的pid删除后 再添加到头上去 addFirst(pid)。如果没有,直接添加到头上。

5.把该集合转为3-2-1字符串形式准备存到cookie。创建StringBuffer  sb。遍历集合,遍历时候加上记录商品的上限,  sb.append(list.get(i)); sb.append("-")

6.把sb字符串去掉最后“-”后赋值给pids, (第一次访问的时候,pids为空,所以默认把当前pid先赋值给pids)

7.创建cookie 把pids存进去,并返回给客户端存储。


接上一个功能在productListByCid中继续完善代码,获取cookie,获得历史商品集合。存到request域中

1.获取cookies,判断是否为空,并获取名字为pids的cookie,获得3-2-1

2.分割该字符串变为数组,[3,2,1],并遍历该数组,查询商品。

3.创建一个集合,用来存储查询到的历史商品historyList

4.把historyList传到request域中。


在product_list.jsp中 

1.jstl 遍历获取historyList,获取每一个历史商品



productServlet

package com.itheima.web.servlet;import java.io.IOException;import java.util.ArrayList;import java.util.Arrays;import java.util.LinkedList;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.Cookie;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 {//商品详细信息页面public void productInfo(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {//获取pidString pid = request.getParameter("pid");//获取当前页String currentPage = request.getParameter("currentPage");//传递到service层获取productProductService service = new ProductService();Product product = service.findProductByPid(pid);//传到request域并转发//传递当前页是准备返回上一级使用的request.setAttribute("product", product);request.setAttribute("currentPage", currentPage);//一下步骤为准备历史记录,记录浏览过商品的pid到cookie//获得客户端原来携带的cookie--名字叫pids的cookieString pids=pid;Cookie[] cookies = request.getCookies();//判断cookies是否为空,如果为空不执行遍历操作if(cookies!=null) {for(Cookie cookie:cookies) {if("pids".equals(cookie.getName())) {//分析:1-3-2   本次访问的pid为0   0-1-3-2//     1-3-2    本次访问为3     3-1-2//获取客户端的pids = cookie.getValue();//将pids拆成一个字符串数组String[] split = pids.split("-");//{3,1,2}List<String> asList = Arrays.asList(split);//[3,1,2]LinkedList<String> list = new LinkedList<String>(asList);//[3,1,2 ]//判断这个集合中是否存在当前pidif(list.contains(pid)) {//包含当前商品的pidlist.remove(pid);list.addFirst(pid);}else {//不包含当前pid,直接放在list头上list.addFirst(pid);}//将[3,1,2 ]转成字符串StringBuffer sb = new StringBuffer();//设置记录历史商品的数量为7个for(int i=0;i<list.size()&&i<7;i++ ) {sb.append(list.get(i));sb.append("-");//3-1-2-}//去掉最后的刚"-"  -3-1-2pids=sb.substring(0, sb.length()-1);}}}//存到cookiesCookie cookie_pids = new Cookie("pids",pids);response.addCookie(cookie_pids);request.getRequestDispatcher("/product_info.jsp").forward(request, response);}//根据商品分类的cid获取商品,分页显示功能public void productListByCid(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {//获取商品分类的cidString cid = request.getParameter("cid");//获取当前页,如果没有当前页,设置为第一页String currentPageStr = request.getParameter("currentPage");if(currentPageStr==null) {currentPageStr ="1";}//当前页,与当前显示数int currentPage = Integer.parseInt(currentPageStr);int currentCount =12;//传递到service层,pageBeanProductService service = new ProductService();PageBean<Product>  pageBean =  service.findPageBeanByCid(cid,currentPage,currentCount);//传递pageBean 与 cid 等待分页下一次执行该功能时候使用request.setAttribute("cid", cid);request.setAttribute("pageBean", pageBean);//以下为显示商品历史记录的代码实现//从cookie获取商品pid//创建一个历史记录容器,准备装上查询到的商品List<Product> historyProductList = new ArrayList<Product>();Cookie[] cookies = request.getCookies();if(cookies!=null) {for(Cookie cookie:cookies) {if("pids".equals(cookie.getName())) {// 获取历史商品的pid 3-2-1String pids = cookie.getValue();//分割成数组pid,遍历查找商品String[] split = pids.split("-");for(String pid:split) {//根据pid查找商品信息Product pro = service.findProductByPid(pid);//把查询到的商品的装起来historyProductList.add(pro);}}}}//把装有历史浏览商品的集合传到request域request.setAttribute("historyProductList", historyProductList);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.jsprequest.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获取pagebeanpublic 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.0int 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;}//根据pid查找商品public Product findProductByPid(String pid) {ProductDao dao = new ProductDao();Product product =null;try {product = dao.findProductByPid(pid);} catch (SQLException e) {e.printStackTrace();}return product;}}


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转为intreturn 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"><!-- 商品详细信息入口 --><!-- 传递currentPage是因为准备返回上一级使用的 --><a href="${pageContext.request.contextPath }/product?method=productInfo&pid=${product.pid}¤tPage=${pageBean.currentPage}"> <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"><spanaria-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><!-- 分页结束 --><!--商品浏览记录--><divstyle="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;"><!-- 显示历史商品记录 --><c:forEach items="${historyProductList }" var="historyPro"><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="${pageContext.request.contextPath }/${historyPro.pimage }" width="130px" height="130px" /></li></ul></c:forEach></div></div><!-- 引入footer.jsp --><jsp:include page="/footer.jsp"></jsp:include></body></html>




阅读全文
0 0