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

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

显示商品详情



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–显示商品详情

相关文章
|
负载均衡 Linux 数据库
阿里云轻量应用服务器套餐收费标准参考(组合套餐、负载均衡套餐等)
阿里云轻量应用服务器有多种套餐,在购买轻量应用服务器、轻量应用负载均衡、轻量容器服务和轻量数据库服务时,我们可以根据业务需求选择合适的套餐。本文为大家介绍阿里云轻量应用服务器套餐和镜像最新价格表以及相关收费说明。
983 0
阿里云轻量应用服务器套餐收费标准参考(组合套餐、负载均衡套餐等)
|
JSON 前端开发 JavaScript
JavaScript拷贝大作战:浅拷贝vs深拷贝
JavaScript拷贝大作战:浅拷贝vs深拷贝
293 0
|
Dubbo 应用服务中间件
java.io.IOException: invalid constant type: 18
java.io.IOException: invalid constant type: 18
932 0
java.io.IOException: invalid constant type: 18
|
JavaScript 应用服务中间件 nginx
vuecli3打包项目上线之后报错怎么使用本地的sourcemap文件定位调试?
vuecli3打包项目上线之后报错怎么使用本地的sourcemap文件定位调试?
313 0
|
关系型数据库 PostgreSQL
|
10月前
|
存储 缓存 Java
写代码原来如此简单:两种常用代码范式
一次项目包含非常多的流程,有需求拆解,业务建模,项目管理,风险识别,代码模块设计等等,如果我们在每次项目中,都将精力大量放在这些过程的思考上面,那我们剩余的,放在业务上思考的精力和时间就会大大减少;这也是为什么我们要 总结经验/方法论/范式 的原因;这篇文章旨在建立代码模块设计上的思路,给出了两种非常常用的设计范式,减少未来在这一块的精力开销。
180 11
|
机器学习/深度学习 编解码 PyTorch
CVPR 2023 | 主干网络FasterNet 核心解读 代码分析
本文分享来自CVPR 2023的论文,提出了一种快速的主干网络,名为FasterNet。核心算子是PConv,partial convolution,部分卷积,通过减少冗余计算和内存访问来更有效地提取空间特征。
9747 58
|
12月前
|
算法 开发者
代码与哲学的交织:探索软件开发中的哲理
【10月更文挑战第17天】 在数字化时代,软件开发不仅仅是技术的堆砌,更是智慧与哲学的碰撞。本文通过深入浅出的方式,探讨了编程中蕴含的哲学思想,如迭代思维、模块化设计以及错误处理的艺术。我们将一起思考如何将这些哲学理念融入日常开发,以提升我们的技术深度和广度,让代码不仅是冰冷的逻辑,而是充满智慧的艺术品。
168 5
|
XML Java 数据库连接
SpringBoot-19-Mybatis的xml配置方式
在上一章节中,我们已经简单介绍mybatis的增删改查的基本操作,基础(单表)的增删改查可以按照,如果稍微复杂一些我们就需要使用mybatis的xml格式去实现。 那么我们开始使用mybatis的xml方式去实现增删改查。
273 0
|
JSON 小程序 JavaScript
【微信小程序】-- 页面事件 - 上拉触底(二十六)
【微信小程序】-- 页面事件 - 上拉触底(二十六)