商城项目第二天笔记

商城项目第二天

今日任务

  • 分类信息的加载
  • 首页最新最热商品展示
  • 商品的详情展示
  • 某个分类下的商品的分页展示

导航菜单

导航实现步骤:

  • 导航菜单显示的是数据库中的商品分类信息
  • 页面加载中,向服务器发送请求
  • Servlet调用业务层方法,获取集合
  • 业务层调用持久层方法
  • Servlet将注册结果封装对象,向客户端回写JSON数据
  • 客户端判断JSON数据,跳转页面

header.html

	//页面加载成功 向服务器发送 查询所有分类信息的请求 
         var url = "/category?method=findAllCategorys";
         var params = "";
         
         HM.ajax(url,params,function(data){
         	  // 处理响应数据 
         	  if(data.code==1){//查询成功
//       	  	   alert(data.message);
                   // 获取分类信息的数组
                   var  cateArr = data.data;
                   
                   var str="";
                   //遍历 
                   $.each(cateArr, function(index,cate) {
                   	   //cate 就是每一个 分类信息 对象   cate.cid序号 cate.cname 名称 
//                 	   str += "<li><a href="#">手机数码</a></li>";
                       str +=`<li><a href="http://www.itheima342.com:8020/web/view/product/list.html?cid=${cate.cid}">${cate.cname}</a></li>`;
                   });
                   
                   $("#cate_list").html(str);
         	  }
         	  
         });

CategoryServlet

 /*
      方法名
     */
    public void findCategorys(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        // 找到所有的分类信息
        List<Category> categorys = categoryService.findCategorys();

       // 封装 Result对象 转换成 json传递给页面
        Result result = new Result(Constant.SUCCESS,"查询成功",categorys);

        String s = JSONObject.fromObject(result).toString();

        response.getWriter().write(s);
    }

CategoryService

 /*
    查询所有的分类信息
     */
    public List<Category> findCategorys() {
        List<Category> list = null;

        try {
            list = categoryDao.findCategorys();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return list;
    }

CategoryDao

   /**
     *   查询所有的分类信息
     * @return
     * @throws SQLException
     */
    public List<Category> findCategorys() throws SQLException {

        String sql = "select * from category";

        return qr.query(sql,new BeanListHandler<>(Category.class));
    }

首页最新最热商品展示

登录实现步骤:

  • 首页加载完成,AJAX向服务器发送请求
  • Servlet调用业务层两次查询方法
  • 业务层分别调用持久层两次方法
  • 持久层两次方法分别查询最热门商品和最新商品
  • Servlet获取两次查询方法结果集,并封装Result对象
  • Result对象转成JSON数据并响应

首页index

<script type="text/javascript">
		  //页面加载完成之后 要将最新最热商品 展示出来
		 $(function(){
		 	// 发送 ajax请求
		 	var url="/product?method=findNewsAndHots";
		 	var params="";
		 	
		 	HM.ajax(url,params,function(data){
		 		
		 		 if(data.code==1){
		 		 	  // data.data  是后端那个map集合 在前端变成了 json对象形式  
		 		 	  
		 		 	   //将商品展示在  页面上!
		 		 	  //最热门商品
		 		 	  var hotsArr = data.data.hots;
		 		 	  
		 		      $.each(hotsArr, function(index,p) {
		 		      	  //每个p就是每件最热门商品  p.pname 商品名
		 		      	  //拼接出每个商品的div
		 		      	  var str=`<div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;">
										<a href="http://www.itheima342.com:8020/web/view/product/info.html?pid=${p.pid}">
											<img src="http://www.itheima342.com:8020/web/${p.pimage}" width="130" height="130" style="display: inline-block;">
										</a>
										<p><a href="http://www.itheima342.com:8020/web/view/product/info.html?pid=${p.pid}" style='color:#666'>${p.pname}</a></p>
										<p><font color="#E4393C" style="font-size:16px">&yen;${p.shop_price}</font></p>
					                </div>`;
		 		      	  
		 		      	  //把拼好的追加到 hotlist里面
		 		      	  $("#hotlist").append(str);
		 		      });
		 		 	  
		 		 	  //最新商品的数组
		 		 	  var newsArr = data.data.news;
		 		 	  
		 		 	  $.each(newsArr, function(index,p) {
		 		      	  //每个p就是每件最新商品  p.pname 商品名
		 		      	  var str=`<div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;">
										<a href="http://www.itheima342.com:8020/web/view/product/info.html?pid=${p.pid}">
											<img src="http://www.itheima342.com:8020/web/${p.pimage}" width="130" height="130" style="display: inline-block;">
										</a>
										<p><a href="http://www.itheima342.com:8020/web/view/product/info.html?pid=${p.pid}" style='color:#666'>${p.pname}</a></p>
										<p><font color="#E4393C" style="font-size:16px">&yen;${p.shop_price}</font></p>
					                </div>`;
		 		      	  
		 		      	  //把拼好的追加到 hotlist里面
		 		      	  $("#newlist").append(str);
		 		      });
		 		 }
		 		
		 	});
		 })
	</script>

ProductServlet

  /*
   查询最新 最热商品
    */
   public void findNewsAndHots(HttpServletRequest request, HttpServletResponse response)
           throws InvocationTargetException, IllegalAccessException,
                  IOException {

       List<Product> news = productService.findNews();
       List<Product> hots = productService.findHots();

       Map<String,List<Product>> map = new HashMap<>();

       map.put("news",news);
       map.put("hots",hots);

       //响应json格式   这种格式 需要跟前端商量!!!

       // 按照 规则 去进行json的响应
       // Result就是规则
       Result result = new Result(Constant.SUCCESS,"查询最新最热",map);

       //需要把 result变成json格式


       response.getWriter().write(JSONObject.fromObject(result).toString());

   }

ProductService

//查询最新
    @Override
    public List<Product> findNews() {
        List<Product> list = null;

        try {
            list=productDao.findNews();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return list;
    }

    //查询最热
    @Override
    public List<Product> findHots() {
        List<Product> list = null;

        try {
            list=productDao.findHots();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return list;
    }

ProductDao

 //查询最新
    @Override
    public List<Product> findNews() throws SQLException {
        String sql = "SELECT * FROM product WHERE pflag=? ORDER BY pdate DESC LIMIT ?";

        Object[] params = { Constant.WEI_XIA_JIA,9};

        return qr.query(sql,new BeanListHandler<>(Product.class),params);
    }
    //查询 最 热门
    @Override
    public List<Product> findHots() throws SQLException {
        String sql = "SELECT * FROM product WHERE pflag=? AND is_hot=? ORDER BY pdate DESC LIMIT ?";

        Object[] params = { Constant.WEI_XIA_JIA,Constant.IS_HOT,9};

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


展示商品详情

实现步骤

  • 首页拼接字符串,将每个商品的主键id传递到详情页面
  • 详情页面获取商品主键,向服务器发送AJAX请求
  • Servlet接收客户端请求的主键值
  • 调用业务层方法,根据主键查询商品
  • 业务层调用持久层查询商品传递,返回商品对象
  • Servlet接收业务层返回的商品对象
  • 商品对象封装Result对象,转成JSON数据,响应浏览器

首页拼接字符串,传递商品主键

//首页添加链接  传递商品主键
 <a href="http://www.itheima342.com:8020/web/view/product/info.html?pid=${p.pid}">

商品详情页面info.html

//页面加载完成
			$(function(){
				//获取 地址栏的参数 
				//alert(location.search)  ?pid=13
				var pid = HM.getParameter("pid");
				
				if(!pid){
					alert("没有此商品");
					location.href="http://www.itheima342.com:8020/web/index.html";
				}
				var url="/product?method=pinfo";
				var params = "pid="+pid;
				HM.ajax(url,params,function(data){
					
					if(data.code==0){
						alert("没有此商品");
					    location.href="http://www.itheima342.com:8020/web/index.html";
					}
					
					if(data.code==1){//查询到了数据
						// 获取 商品对象
						var p = data.data;
						//商品详情设置到页面上
						
						$("#pname").html(p.pname);
						$("#pid").html("编号:"+p.pid);
						$("#shop_price").html(p.shop_price);
						$("#market_price").html("¥"+p.market_price+"元");
                        $("#pimage").attr("src","http://www.itheima342.com:8020/web/"+p.pimage);
                        $("#smallImg").attr("src","http://www.itheima342.com:8020/web/"+p.pimage);
                        $("#pdesc").html(p.pdesc);
                        
					}
					
				})
				
			})
			

ProductServlet

 /*
       根据pid查询商品详情
      */
    public void pinfo(HttpServletRequest request, HttpServletResponse response)
            throws InvocationTargetException, IllegalAccessException,
                   IOException {

        String pid = request.getParameter("pid");
        // 传递给service
        Product product= productService.pinfo(pid);

        if(product==null){
            Result result = new Result(Constant.FAILS,"未查到此商品");

            //需要把 result变成json格式


            response.getWriter().write(JSONObject.fromObject(result).toString());

            return;
        }
        //有商品 就执行下面
        Result result = new Result(Constant.SUCCESS,"查询商品详情成功",product);

        response.getWriter().write(JSONObject.fromObject(result).toString());
    }

ProductService

 @Override
    public Product pinfo(String pid) {
        Product product = null;

        try {
            product=productDao.pinfo(pid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return product;
    }

ProductDao

 // 根据pid查询指定的商品信息
    @Override
    public Product pinfo(String pid) throws SQLException {
       String sql = "select * from product where pid=?";
       Object[] params={pid};
        return qr.query(sql, new BeanHandler<>(Product.class), params);
    }

查询每个分类下的商品详情

实现步骤

  • 菜单页面拼接超链接,传递商品分类主键
  • 分类商品页面接收分类主键数据,向服务器发送AJAX请求
  • Servlet接收客户端分类主键的数据
  • 调用业务层方法组装PageBean数据
  • 业务层调用持久层方法,分页查询数据表
  • Servlet接收业务层返回的PageBean数据,转成JSON响应客户端

header页面添加连接

str += `<li><a href="http://www.itheima342.com:8020/web/view/product/list.html?cid=${c.cid}">${c.cname}</a></li>`;

list 商品分页展示页面

//页面加载
					// 页面加载   发送ajax请求
			$(function(){
				
				var cid=HM.getParameter("cid");
				
				var pageNumber=HM.getParameter("pageNumber");
				
				if(!pageNumber){
					
					pageNumber=1;
				}
				
				var url="/product?method=findProductsByCid";
				
				var params="cid="+cid+"&pageNumber="+pageNumber;
				
				
				HM.ajax(url,params,function(data){
					   
					   //data.data 是什么 
					   var pb = data.data;
					   //{"pageNumber":1,"pageSize":12...... }
					   // paArray是查询出来当页商品的数组
					   var pArray = pb.data;
					   
					  $.each(pArray, function(index,p) {
					  	//p就是每一个商品
					  		  //拼接出每个商品的div
		 		      	  var str=`<div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;">
										<a href="http://www.itheima342.com:8020/web/view/product/info.html?pid=${p.pid}">
											<img src="http://www.itheima342.com:8020/web/${p.pimage}" width="130" height="130" style="display: inline-block;">
										</a>
										<p><a href="http://www.itheima342.com:8020/web/view/product/info.html?pid=${p.pid}" style='color:#666'>${p.pname}</a></p>
										<p><font color="#E4393C" style="font-size:16px">&yen;${p.shop_price}</font></p>
					                </div>`;
					                
					        $("#productlist").append(str);        
					  });
					
					  var page = HM.page(pb,"http://www.itheima342.com:8020/web/view/product/list.html?cid="+cid);
					                         //url去掉pageNumber
					  
					  $("#page").html(page);
				});
			})

ProductServlet

/*
       根据某一分类下的商品信息  采用 分页操作
      */
    public void findProductsByCid(HttpServletRequest request, HttpServletResponse response)
            throws InvocationTargetException, IllegalAccessException,
                   IOException {

        //1:获取 参数  cid pageNumber
        String cid = request.getParameter("cid");
        int pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
        //设置一个 pageSize
        int pageSize =12;


        // 2:找到service对象 完成封装pageBean
        PageBean<Product> pb = productService
                .getPageBeanByCid(cid, pageNumber, pageSize);

        //有商品 就执行下面
        Result result = new Result(Constant.SUCCESS,"查询分类商品成功",pb);

        response.getWriter().write(JSONObject.fromObject(result).toString());
    }

ProductService

   /**
     *    封装 某一页数据 也就是 pageBean对象
     * @param cid
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @Override
    public PageBean<Product> getPageBeanByCid(String cid, int pageNumber,
                                              int pageSize) {
        PageBean<Product> pageBean = new PageBean<>();

        try {
            //查询 当前分类下的商品总条数
            int total = (int)productDao.findTotalByCid(cid);

            pageBean.setTotal(total);
            pageBean.setPageNumber(pageNumber);
            pageBean.setPageSize(pageSize);
            pageBean.setTotalPage((int)Math.ceil(total*1.0/pageSize));

            // 获取 当前页数据
            List<Product> products = productDao
                    .findProductsByCid(cid, pageNumber, pageSize);

            // 数据存在 pagebean对象中
            pageBean.setData(products);

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return pageBean;
    }

ProductDao

/*
     查询某个分类下商品的总条数
     */
    @Override
    public long findTotalByCid(String cid) throws SQLException {
        String sql = "select count(*) from product where cid = ?";
        Object[] params = {cid};
        return qr.query(sql, new ScalarHandler<>(), params);
    }
   /*
     查询 某个分页下 商品信息  根据分页操作查询
    */
    @Override
    public List<Product> findProductsByCid(String cid, int pageNumber,
                                           int pageSize) throws SQLException {
        // 查询某一页数据

        String sql = "select * from product where cid=? limit ?,?";
        Object[] params = {cid,(pageNumber-1)*pageSize,pageSize};



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

猜你喜欢

转载自blog.csdn.net/qq_35670694/article/details/89080129