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

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

显示商品详情



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

相关文章
|
存储 缓存 关系型数据库
|
1天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8067 2
|
11天前
|
域名解析 人工智能 Linux
|
21天前
|
Linux Go 开发工具
手机上跑 DeepSeek 智能体:开源安卓客户端 DSH Go 安装与使用指南
DSH Go 是一款开源安卓客户端,将 DeepSeek Harness 智能体引擎装进手机:免 Root、免 Termux,一键安装即用;支持本机运行(内置 Ubuntu+Node.js)或远程接管电脑会话;具备插话打断、过程折叠、屏幕操控、端到端加密分享等特色功能,真正实现智能体“口袋化”。
18474 64
|
19天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
5天前
|
人工智能 安全 网络安全
|
9天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是 DeepSeek AI 开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、执行命令、处理表格等自动化任务;免费开源,兼容 Win/macOS,需配 API 密钥使用。(239字)
1500 5
|
8天前
|
云安全 数据采集 人工智能
|
16天前
|
人工智能 开发工具 开发者
2026最新codex下载安装保姆级使用教程(下载+安装+登录+使用,含所有历史版本)
Codex 是 OpenAI 推出的开源 AI 编程智能体,跑在本地终端和桌面客户端里,能读懂整个代码仓库,一句自然语言就能让它改代码、执行命令、跑测试、修 Bug,支持 Windows、macOS、Linux 三大平台。本文把 Codex下载、安装、登录、汉化、基础使用一次讲全,并整理了国内用户最常踩的坑,跟着做 10 分钟就能跑起来。
2641 8