显示商品详情【项目 商城】

简介: 显示商品详情【项目 商城】

显示商品详情



1.商品显示商品详情持久层

1.1 规划查询的SQL语句

根据商品的id显示商品详情的SQL语句

SELECT * FROM t_product WHERE id=?

1.2 实现接口与抽象方法

在ProductMapper接口中添加抽象方法。

/* 根据商品id查询商品详情*/
    Product findById(Integer id);

1.3 配置SQL映射

1.在ProductMapper.xml文件中配置findById(Integer id)方法的映射。

    <!-- 根据商品id查询商品详情:Product findById(Integer id) -->
    <select id="findById" resultMap="ProductEntityMap">
        SELECT * FROM t_product WHERE id=#{id}
    </select>

ProductMapper–findById


测试

ProductMapperTests

package com.up.stores.mapper;
import com.up.stores.entity.Product;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ProductMapperTests {
    @Autowired
    private ProductMapper productMapper;
    @Test
    public void findHotList() {
        List<Product> list = productMapper.findHotList();
        System.out.println("count=" + list.size());
        for (Product item : list) {
            System.out.println(item);
        }
    }
    @Test
    public void findById() {
        Integer id = 10000017;
        Product result = productMapper.findById(id);
        System.out.println(result);
    }
}

ProductMapperTests


2.商品显示商品详情业务层

2.1 规划异常

如果商品数据不存在,一个抛出ProductNotFoundException,需要创建异常。

package com.cy.store.service.ex;
/** 商品数据不存在的异常 */
public class ProductNotFoundException extends ServiceException {
    public ProductNotFoundException() {
    }
    public ProductNotFoundException(String message) {
        super(message);
    }
    public ProductNotFoundException(String message, Throwable cause) {
        super(message, cause);
    }
    public ProductNotFoundException(Throwable cause) {
        super(cause);
    }
    public ProductNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

ProductNotFoundException


2.2 实现接口与抽象方法

在业务层IProductService接口中添加findById(Integer id)抽象方法。

  /*根据商品id查询商品详情*/
    Product findById(Integer id);

2.3 实现抽象方法

1.在ProductServiceImpl类中,实现接口中的findByd(Integer id)抽象方法.

  @Override
    public Product findById(Integer id) {
        // 根据参数id调用私有方法执行查询,获取商品数据
        Product product = productMapper.findById(id);
        // 判断查询结果是否为null
        if (product == null) {
            // 是:抛出ProductNotFoundException
            throw new ProductNotFoundException("尝试访问的商品数据不存在");
        }
        // 将查询结果中的部分属性设置为null
        product.setPriority(null);
        product.setCreatedUser(null);
        product.setCreatedTime(null);
        product.setModifiedUser(null);
        product.setModifiedTime(null);
        // 返回查询结果
        return product;
    }

ProductService–findById


测试

package com.cy.store.service;
import com.cy.store.entity.Product;
import com.cy.store.service.ex.ServiceException;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
public class ProductServiceTests {
    @Autowired
    private IProductService productService;
    @Test
    public void findHotList() {
        try {
            List<Product> list = productService.findHotList();
            System.out.println("count=" + list.size());
            for (Product item : list) {
                System.out.println(item);
            }
        } catch (ServiceException e) {
            System.out.println(e.getClass().getSimpleName());
            System.out.println(e.getMessage());
        }
    }
    @Test
    public void findById() {
        try {
            Integer id = 10000042;
            Product result = productService.findById(id);
            System.out.println(result);
        } catch (ServiceException e) {
            System.out.println(e.getClass().getSimpleName());
            System.out.println(e.getMessage());
        }
    }
}

**ProductServiceTests **


3.商品显示商品详情控制器

3.1 处理异常

在BaseController类中处理ProductNotFoundException

    else if (e instanceof ProductNotFoundException) {
            result.setState(4006);
            result.setMessage("商品数据不存在的异常");
        }

BaseController–ProductNotFoundException


3.2 设计请求

请求路径:/products/{id}/details
请求参数:@PathVariable("id") Integer id
请求类型:GET
响应结果:JsonResult<Product>

3.3 处理请求

1.在ProductController类中添加处理请求的getById()方法

  @GetMapping("{id}/details")
    public JsonResult<Product> getById(@PathVariable("id") Integer id) {
        // 调用业务对象执行获取数据
        Product data = productService.findById(id);
        // 返回成功和数据
        return new JsonResult<Product>(OK, data);
    }

ProductController–getById


测试

2.完成或启动项目,直接访问测试。

4 商品详情页–前端页面

1.检查在product.html页面body标签内部的最后是否引入jquery-getUrlParam.js文件,如果引入无需重复引入。

<script type="text/javascript" src="../js/jquery-getUrlParam.js"></script>

2.在product.html页面中body标签内部的最后,添加获取当前商品详情的代码。

    <script type="text/javascript">
      let id = $.getUrlParam("id");
      console.log("id=" + id);
      $(document).ready(function() {
        $.ajax({
          url: "/products/" + id + "/details",
          type: "GET",
          dataType: "JSON",
          success: function(json) {
            if (json.state == 200) {
              console.log("title=" + json.data.title);
              $("#product-title").html(json.data.title);
              $("#product-sell-point").html(json.data.sellPoint);
              $("#product-price").html(json.data.price);
              for (let i = 1; i <= 5; i++) {
                $("#product-image-" + i + "-big").attr("src", ".." + json.data.image + i + "_big.png");
                $("#product-image-" + i).attr("src", ".." + json.data.image + i + ".jpg");
              }
            } else if (json.state == 4006) { // 商品数据不存在的异常
              location.href = "index.html";
            } else {
              alert("获取商品信息失败!" + json.message);
            }
          }
        });
      });
      $("#btn-add-to-cart").click(function(){
        $.ajax({
          url: "/carts/add_to_cart",
          type: "POST",
          data: {
            "pid": id,
            "amount":$("#num").val()
          },
          dataType: "JSON",
          success: function(json) {
            if (json.state == 200) {
              alert("加入购物车成功!");
            } else {
              alert("加入购物车失败!");
            }
          },
          error: function(xhr) {
            alert("加入购物车产生未知异常" + xhr.message);
          }
        });
      });
    </script>

product.html


测试

完成后启动项目进行测试。

README–显示商品详情

相关文章
|
5月前
|
JSON API 开发者
淘宝获取购物车的商品列表 API接口
淘宝提供了获取购物车商品列表 API 接口,允许开发者通过编程方式获取用户购物车中的商品列表。这个 API 接口可以帮助开发者更好地了解用户在购物车中添加了哪些商品,以及每个商品的基本信息,例如商品 ID、名称、价格、数量等。
|
8月前
|
XML JSON API
淘宝天猫API接入说明(淘宝天猫商品详情+关键词搜索商品列表)商品详情数据,商品sku数据,商品优惠券数据
业务场景:作为全球最大的 B2C 电子商务平台之一,淘宝天猫平台提供了丰富的商品资源,吸引了大量的全球买家和卖家。为了方便开发者接入淘宝天猫平台,淘宝天猫平台提供了丰富的 API 接口,其中历史价格接口是非常重要的一部分。大家有探讨稳定采集淘宝(天猫)京东阿里拼多多等平台整站实时商品详情历史价格数据接口,通过该接口开发者可以更好地了解商品的情况,商品详情数据详细信息查询,数据参数包括:商品链接,商品列表主图、价格、标题,sku,库存,销量,店铺昵称,店铺等级,商品详情SKU属性,商品视频,商品优惠券,促销信息,详情属性描述,宝贝ID,区域ID,发货地,发货至,快递费用,物流费用等页面上有的数据
|
2月前
|
API 开发工具 数据安全/隐私保护
API接口的对接流程和注意事项(淘宝商品详情店铺)
随着互联网技术的发展和应用的普及,API接口已经成为不同系统、不同应用之间进行交互和数据交换的重要方式。API接口使得不同的系统能够互相调用对方的功能,提高了系统的灵活性和扩展性。但是,在进行API接口对接的过程中,需要注意一些流程和事项,以确保对接的顺利进行和系统的稳定运行。
|
9月前
|
SQL 存储 前端开发
显示购物车列表【项目 商城】
显示购物车列表【项目 商城】
37 0
|
9月前
|
SQL 前端开发 测试技术
显示勾选的购物车数据【项目 商城】
显示勾选的购物车数据【项目 商城】
44 0
|
6月前
|
JSON JavaScript 前端开发
使用商品详情API接口获取商品数据
在电子商务领域,商品详情API接口是一种常用的工具,用于从服务器获取特定商品的详细信息。通过使用这些API接口,开发人员可以轻松地获取商品的名称、价格、描述、图片等数据,从而为用户提供更好的购物体验。本文将详细介绍如何使用商品详情API接口来获取想要的商品数据,并提供相关的代码示例。
|
6月前
|
JSON 缓存 API
如何使用商品详情API接口来获取想要的商品数据?
在这篇文章中,我将详细介绍如何使用商品详情API接口来获取想要的商品数据。首先,我们需要了解API接口的基本概念和使用方法。然后,我们将探讨如何通过API接口获取商品数据,并给出示例代码。最后,我们将讨论如何优化API接口的使用,以提高获取商品数据的效率。
|
9月前
|
SQL XML 前端开发
收货地址列表展示【项目 商城】
收货地址列表展示【项目 商城】
66 0
|
10月前
|
前端开发 JavaScript
商城业务:商品详情
商城业务:商品详情
|
11月前
|
API