乐优商城学习笔记十八-商品详情


title: 乐优商城学习笔记十八-商品详情
date: 2019-04-21 10:53:45
tags:
- 乐优商城
- java
- springboot
categories:
- 乐优商城


上传图片失败,可以查看作者github博客链接:
https://smallmartial.github.io/blog

0.学习目标

  • 了解Thymeleaf的基本使用
  • 实现商品详情页的渲染
  • 知道页面静态化的作用
  • 实现页面静态化功能

1.商品详情

当用户搜索到商品,肯定会点击查看,就会进入商品详情页,接下来我们完成商品详情页的展示,

1.2.商品详情页服务

商品详情浏览量比较大,并发高,我们会独立开启一个微服务,用来展示商品详情。

1.2.1.创建module

商品的详情页服务,命名为:ly-goods-page

1.2.2.pom依赖



    
        leyou
        com.leyou.parent
        1.0.0-SNAPSHOT
    
    4.0.0

    com.leyou.service
    ly-goods-page
    1.0.0-SNAPSHOT

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        
        
            org.springframework.cloud
            spring-cloud-starter-openfeign
        
        
            com.leyou.service
            ly-item-interface
            ${leyou.latest.version}
        
    

1.2.3.编写启动类:

@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication
public class LyGoodsPage {
    public static void main(String[] args) {
        SpringApplication.run(LyGoodsPage.class, args);
    }
}

1.2.4.application.yml文件

sringboot版本 2.1.0以上 添加以下内容
main:

allow-bean-definition-overriding: true
server:
  port: 8084

spring:
  application:
    name: page-service
  thymeleaf:
    cache: false
  main:
    allow-bean-definition-overriding: true
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka
  instance:
    lease-renewal-interval-in-seconds: 5 # 每隔5秒发送一次心跳
    lease-expiration-duration-in-seconds: 10 # 10秒不发送就过期
    prefer-ip-address: true
    ip-address: 127.0.0.1
    instance-id: ${spring.application.name}.${server.port}

1.2.5.页面模板:

建议从博主的github 下载一下该页面,编写过程中前端存在各种坑
https://github.com/smallmartial/lyshop.git

1526971729051

1.3.页面跳转

1.3.1.修改页面跳转路径

首先我们需要修改搜索结果页的商品地址,目前所有商品的地址都是:http://www.leyou.com/item.html

[图片上传失败...(image-34598b-1555816499191)]

我们应该跳转到对应的商品的详情页才对。

那么问题来了:商品详情页是一个SKU?还是多个SKU的集合?

[图片上传失败...(image-9b3ced-1555816499191)]

通过详情页的预览,我们知道它是多个SKU的集合,即SPU。

所以,页面跳转时,我们应该携带SPU的id信息。

例如:http://www.leyou.com/item/2314123.html

这里就采用了路径占位符的方式来传递spu的id,我们打开search.html,修改其中的商品路径:

[图片上传失败...(image-867a3a-1555816499191)]

刷新页面后在看:

[图片上传失败...(image-40d39c-1555816499191)]

1.3.2.nginx反向代理

接下来,我们要把这个地址指向我们刚刚创建的服务:ly-goods-page,其端口为8084

我们在nginx.conf中添加一段逻辑:

[图片上传失败...(image-3e2013-1555816499191)]

把以/item开头的请求,代理到我们的8084端口

1.3.3.编写跳转controller

ly-goods-page中编写controller,接收请求,并跳转到商品详情页:

@Controller
@RequestMapping("item")
public class GoodsController {

    /**
     * 跳转到商品详情页
     * @param model
     * @param id
     * @return
     */
    @GetMapping("{id}.html")
    public String toItemPage(Model model, @PathVariable("id")Long id){

        return "item";
    }
}

[图片上传失败...(image-5a5aae-1555816499191)]

1.3.4.测试

启动ly-goods-page,点击搜索页面商品,看是能够正常跳转:

[图片上传失败...(image-2fccb6-1555816499191)]

现在看到的依然是静态的数据。我们接下来开始页面的渲染

1.4.封装模型数据

首先我们一起来分析一下,在这个页面中需要哪些数据

我们已知的条件是传递来的spu的id,我们需要根据spu的id查询到下面的数据:

  • spu信息(无)
  • spu的详情
  • spu下的所有sku
  • 品牌
  • 商品三级分类
  • 商品规格参数、规格参数组(无)

1.4.1.商品微服务提供接口

查询spu接口

以上所需数据中,查询spu的接口目前还没有,我们需要在商品微服务中提供这个接口:

GoodsApi

/**
 * 根据spu的id查询spu
 * @param id
 * @return
 */
@GetMapping("spu/{id}")
Spu querySpuById(@PathVariable("id") Long id);

GoodsController

@GetMapping("spu/{id}")
public ResponseEntity querySpuById(@PathVariable("id") Long id){
    Spu spu = this.goodsService.querySpuById(id);
    if(spu == null){
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
    return ResponseEntity.ok(spu);
}

GoodsService

    public Spu querySpuById(Long id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //查询sku
        spu.setSkus(querySkuSpuId(id));
        //查询detail
        spu.setSpuDetail(querySpuDetailById(id));

        return spu;
    }

查询规格参数组

我们在页面展示规格时,需要按组展示:

[图片上传失败...(image-70e094-1555816499191)]

组内有多个参数,为了方便展示。我们提供一个接口,查询规格组,同时在规格组中持有组内的所有参数。

拓展SpecGroup类:

我们在SpecGroup中添加一个SpecParam的集合,保存改组下所有规格参数

@Table(name = "tb_spec_group")
public class SpecGroup {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private Long cid;

    private String name;

    @Transient
    private List params; // 该组下的所有规格参数集合
}

然后提供查询接口:

SpecificationAPI:

public interface SpecificationApi {
    @GetMapping("spec/params")
    List querySpecSpecParam(
            @RequestParam(value = "gid",required = false) Long gid,
            @RequestParam(value="cid", required = false) Long cid,
            @RequestParam(value="searching", required = false) Boolean searching,
            @RequestParam(value="generic", required = false) Boolean generic);

    @GetMapping("spec/group")
    List queryGroupByCid(@RequestParam("cid") Long cid);
}

SpecificationController

    @GetMapping("group")
    public ResponseEntity> queryListByCid(@RequestParam("cid") Long cid){
        return  ResponseEntity.ok(specificationService.queryListByCid(cid));
    }

SpecificationService

    public List queryListByCid(Long cid) {
        //查询规格参数
        List specGroups = queryBySpecGroups(cid);
        //查询当前分类下的参数
        List specParams = querySpecParams(null, cid, null,null);
        //先把规格参数变成map,map的key是规格组的id,map的值是组下的所有参数
        Map> map = new HashMap<>();
        for (SpecParam specParam : specParams) {
            if (!map.containsKey(specParam.getGroupId())){
                map.put(specParam.getGroupId(),new ArrayList<>());
            }
            map.get(specParam.getGroupId()).add(specParam);
        }

        //填充param到group
        for (SpecGroup specGroup : specGroups) {
            specGroup.setParams(map.get(specGroup.getId()));
        }


        return specGroups;
    }
}

1.4.2.创建FeignClient

我们在ly-goods-page服务中,创建FeignClient:

[图片上传失败...(image-ebcdd5-1555816499191)]

BrandClient:

@FeignClient("item-service")
public interface BrandClient extends BrandApi {
}

CategoryClient

@FeignClient("item-service")
public interface CategoryClient extends CategoryApi {
}

GoodsClient:

@FeignClient("item-service")
public interface GoodsClient extends GoodsApi {
}

SpecificationClient:

@FeignClient(value = "item-service")
public interface SpecificationClient extends SpecificationApi{
}

1.4.3.封装数据模型

我们创建一个GoodsService,在里面来封装数据模型。

这里要查询的数据:

  • SPU

  • SKU集合

  • 商品分类

    • 这里值需要分类的id和name就够了,因此我们查询到以后自己需要封装数据
  • 品牌

  • 规格组

    • 查询规格组的时候,把规格组下所有的参数也一并查出,上面提供的接口中已经实现该功能,我们直接调
  • sku的特有规格参数

    有了规格组应该不需要再查询规格参数才对了,为什么这里还要查询?

    因为在SpuDetail中的SpecialSpec中,是以id作为规格参数id作为key,如图:

    [图片上传失败...(image-7443ab-1555816499191)]

    但是,在页面渲染时,需要知道参数的名称,如图:

    [图片上传失败...(image-81c1a0-1555816499191)]

    我们就需要把id和name一一对应起来,因此需要额外查询sku的特有规格参数,然后变成一个id:name的键值对格式。也就是一个Map,方便将来根据id查找!

Service代码

/**
 * @Author smallmartial
 * @Date 2019/4/20
 * @Email [email protected]
 */
@Service
public class PageService {
    @Autowired
    private BrandClient brandClient;
    @Autowired
    private CategoryClient categoryClient;
    @Autowired
    private GoodClient goodsClient;
    @Autowired
    private SpecificationClient specClient;

    public Map loadModel(Long id) {
        Map model = new HashMap<>();
        //查询spu
        Spu spu = goodsClient.querySpuById(id);
        //查询skus
        List skus =spu.getSkus();
        //查询详情
        SpuDetail detail = spu.getSpuDetail();
       // String specialSpec = detail.getSpecialSpec();
        //查询brand
        Brand brand = brandClient.queryBrandById(spu.getBrandId());
      //  Brand brand = this.brandClient.queryBrandByIds(Collections.singletonList(spu.getBrandId())).get(0);
        // 准备品牌数据
        List brands = this.brandClient.queryBrandByIds(
                Arrays.asList(spu.getBrandId()));
        //查询商品分类
        List categories = categoryClient.queryCategoryByIds(
                Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
        //查询规格参数
        List specs = specClient.queryGroupByCid(spu.getCid3());
        //查询规格参数(附加)


        // 查询规格组及组内参数
        List groups = specClient.queryGroupByCid(spu.getCid3());

        // 查询商品分类下的特有规格参数
        List params =
                this.specClient.querySpecSpecParam(null, spu.getCid3(), null, false);
        // 处理成id:name格式的键值对
        Map paramMap = new HashMap<>();
        for (SpecParam param : params) {
            paramMap.put(param.getId(), param.getName());
        }
        /**
         * 对于规格属性的处理需要注意以下几点:
         *      1. 所有规格都保存为id和name形式
         *      2. 规格对应的值保存为id和value形式
         *      3. 都是map形式
         *      4. 将特有规格参数单独抽取
         */
        //获取所有规格参数,然后封装成id和name形式的数据
//        String allSpecJson = detail.getSpecialSpec();
//        List> allSpecs = JsonUtils
//                .nativeRead(allSpecJson, new TypeReference>>() {});
//        Map specName = new HashMap<>();
//        Map specValue = new HashMap<>();
//        this.getAllSpecifications(allSpecs,specName,specValue);

        //获取特有规格参数
        model.put("title",spu.getTitle());
        model.put("subTitle",spu.getSubTitle());
        model.put("skus",skus);
        model.put("detail",detail);
        model.put("brand",brand);
        model.put("categories",categories);
        model.put("specs",specs);
        model.put("paramMap", paramMap);
        model.put("groups", groups);
      //  model.put("specialSpec");
        return model;
    }
}

然后在controller中把数据放入model:

@Controller
@RequestMapping("item")
public class GoodsController {


    @Autowired
    private GoodsService goodsService;
    /**
     * 跳转到商品详情页
     * @param model
     * @param id
     * @return
     */
    @GetMapping("{id}.html")
    public String toItemPage(Model model, @PathVariable("id")Long id){
        // 加载所需的数据
        Map modelMap = this.goodsService.loadModel(id);
        // 放入模型
        model.addAllAttributes(modelMap);
        return "item";
    }
}

1.4.4.页面测试数据

我们在页面中先写一段JS,把模型中的数据取出观察,看是否成功:


然后查看页面源码:

[图片上传失败...(image-3699f3-1555816499191)]

数据都成功查到了!

1.5.渲染面包屑

在商品展示页的顶部,有一个商品分类、品牌、标题的面包屑

[图片上传失败...(image-9aea3-1555816499191)]

其数据有3部分:

  • 商品分类
  • 商品品牌
  • spu标题

我们的模型中都有,所以直接渲染即可(页面37行开始):

1.6.渲染商品列表

先看下整体效果:

[图片上传失败...(image-ac6aa-1555816499191)]

这个部分需要渲染的数据有5块:

  • sku图片
  • sku标题
  • 副标题
  • sku价格
  • 特有规格属性列表

其中,sku 的图片、标题、价格,都必须在用户选中一个具体sku后,才能渲染。而特有规格属性列表可以在spuDetail中查询到。而副标题则是在spu中,直接可以在页面渲染

因此,我们先对特有规格属性列表进行渲染。等用户选择一个sku,再通过js对其它sku属性渲染

1.6.1.副标题

副标题是在spu中,所以我们直接通过Thymeleaf渲染:

在第87行左右:

副标题中可能会有超链接,因此这里也用th:utext来展示,效果:

[图片上传失败...(image-d56e3b-1555816499191)]

1.6.2.渲染规格属性列表

规格属性列表将来会有事件和动态效果。我们需要有js代码参与,不能使用Thymeleaf来渲染了。

因此,这里我们用vue,不过需要先把数据放到js对象中,方便vue使用

初始化数据

我们在页面的head中,定义一个js标签,然后在里面定义变量,保存与sku相关的一些数据:


  • specialSpec:这是SpuDetail中与唯一与Sku相关的数据

    因此我们并没有保存整个spuDetail,而是只保留了这个属性,而且需要手动转为js对象。

  • paramMap:规格参数的id和name对,方便页面根据id获取参数名

  • specialSpec:特有规格参数集合

我们来看下页面获取的数据:

[图片上传失败...(image-adcae6-1555816499191)]

通过Vue渲染

我们把刚才获得的几个变量保存在Vue实例中:

[图片上传失败...(image-501f5a-1555816499191)]

然后在页面中渲染:


然后刷新页面查看:

[图片上传失败...(image-216e19-1555816499191)]

数据成功渲染了。不过我们发现所有的规格都被勾选了。这是因为现在,每一个规格都有样式:selected,我们应该只选中一个,让它的class样式为selected才对!

那么问题来了,我们该如何确定用户选择了哪一个?

1.6.3.规格属性的筛选

分析

规格参数的格式是这样的:

[图片上传失败...(image-a2d1c6-1555816499191)]

每一个规格项是数组中的一个元素,因此我们只要保存被选择的规格项的索引,就能判断哪个是用户选择的了!

我们需要一个对象来保存用户选择的索引,格式如下:

{
    "4":0,
    "12":0,
    "13":0
}

但问题是,第一次进入页面时,用户并未选择任何参数。因此索引应该有一个默认值,我们将默认值设置为0。

我们在head的script标签中,对索引对象进行初始化:

[图片上传失败...(image-152505-1555816499191)]

然后在vue中保存:

[图片上传失败...(image-d03582-1555816499191)]

页面改造

我们在页面中,通过判断indexes的值来判断当前规格是否被选中,并且给规格绑定点击事件,点击规格项后,修改indexes中的对应值:


效果:

[图片上传失败...(image-799903-1555816499191)]

vue实例中的索引会随着你的点击而变化:

[图片上传失败...(image-91d416-1555816499191)]

1.6.4.确定SKU

在我们设计sku数据的时候,就已经添加了一个字段:indexes:

[图片上传失败...(image-faf304-1555816499191)]

这其实就是规格参数的索引组合。

而我们在页面中,用户点击选择规格后,就会把对应的索引保存起来:

[图片上传失败...(image-d1741f-1555816499191)]

因此,我们可以根据这个indexes来确定用户要选择的sku

我们在vue中定义一个计算属性,来计算与索引匹配的sku:

computed:{
    sku(){
        const index = Object.values(this.indexes).join("_");
        return this.skus.find(s => s.indexes = index);
    }
}

在浏览器工具中查看:

[图片上传失败...(image-9eff79-1555816499191)]

1.6.5.渲染sku列表

既然已经拿到了用户选中的sku,接下来,就可以在页面渲染数据了

图片列表

商品图片是一个字符串,以,分割,页面展示比较麻烦,所以我们编写一个计算属性,将图片字符串变成数组:

images(){
    return this.sku.images ? this.sku.images.split(",") : ['']
}

页面改造:

[图片上传失败...(image-e4d5e-1555816499191)]

效果:

[图片上传失败...(image-83f780-1555816499191)]

标题和价格

[图片上传失败...(image-c0078e-1555816499191)]

完整效果

[图片上传失败...(image-70efa-1555816499191)]

1.7.商品详情

商品详情页面如下图所示:

[图片上传失败...(image-c2646e-1555816499191)]

分成上下两部分:

  • 上部:展示的是规格属性列表
  • 下部:展示的是商品详情

1.7.2.商品详情

商品详情是HTML代码,我们不能使用 th:text,应该使用th:utext

在页面的第420行左右:


最终展示效果:

[图片上传失败...(image-ce8a56-1555816499191)]

1.8.规格包装:

规格包装分成两部分:

  • 规格参数
  • 包装列表

而且规格参数需要按照组来显示

1.8.1.规格参数

最终的效果:

[图片上传失败...(image-b388fb-1555816499191)]

我们模型中有一个groups,跟这个数据结果很像:

[图片上传失败...(image-2768d8-1555816499191)]

分成8个组,组内都有params,里面是所有的参数。不过,这些参数都没有值!

规格参数的值分为两部分:

  • 通用规格参数:保存在SpuDetail中的genericSpec中
  • 特有规格参数:保存在sku的ownSpec中

我们需要把这两部分值取出来,放到groups中。

因为sku是动态的,所以我们编写一个计算属性,来进行值的组合:

groups(){
    groups.forEach(group => {
        group.params.forEach(param => {
            if(param.generic){
                // 通用属性,去spu的genericSpec中获取
                param.v = this.genericSpec[param.id] || '其它';
            }else{
                // 特有属性值,去SKU中获取
                param.v = JSON.parse(this.sku.ownSpec)[param.id]
            }
        })
    })
    return groups;
}

然后在页面渲染:

{{group.name}}

{{p.name}}
{{p.v + (p.unit || '')}}

1.8.2.包装列表

包装列表在商品详情中,我们一开始并没有赋值到Vue实例中,但是可以通过Thymeleaf来渲染

包装清单

最终效果:

[图片上传失败...(image-932490-1555816499192)]

[图片上传失败...(image-bddf5c-1555816499192)]

1.9.售后服务

售后服务也可以通过Thymeleaf进行渲染:

售后保障

效果:

[图片上传失败...(image-51214-1555816499192)]

你可能感兴趣的:(乐优商城学习笔记十八-商品详情)