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

0.学习目标

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

1.商品详情

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

1.2.商品详情页服务

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

1.2.1.创建module

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

1.2.2.pom依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>leyou</artifactId>
        <groupId>com.leyou.parent</groupId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.leyou.service</groupId>
    <artifactId>ly-goods-page</artifactId>
    <version>1.0.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>com.leyou.service</groupId>
            <artifactId>ly-item-interface</artifactId>
            <version>${leyou.latest.version}</version>
        </dependency>
    </dependencies>
</project>

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

1526955707685

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

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

1526955852490

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

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

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

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

1526972476737

刷新页面后在看:

1526972581134

1.3.2.nginx反向代理

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

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

1526973608829

把以/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";
    }
}

1526973726422

1.3.4.测试

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

1526973800526

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

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<Spu> 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;
    }
查询规格参数组

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

1526995904991

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

拓展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<SpecParam> params; // 该组下的所有规格参数集合
}

然后提供查询接口:

SpecificationAPI:

public interface SpecificationApi {
    @GetMapping("spec/params")
    List<SpecParam> 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<SpecGroup> queryGroupByCid(@RequestParam("cid") Long cid);
}

SpecificationController

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

SpecificationService

    public List<SpecGroup> queryListByCid(Long cid) {
        //查询规格参数
        List<SpecGroup> specGroups = queryBySpecGroups(cid);
        //查询当前分类下的参数
        List<SpecParam> specParams = querySpecParams(null, cid, null,null);
        //先把规格参数变成map,map的key是规格组的id,map的值是组下的所有参数
        Map<Long,List<SpecParam>> 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:

1529916126099

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,如图:

    1529922634977

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

    1529922667759

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

Service代码

/**
 * @Author smallmartial
 * @Date 2019/4/20
 * @Email smallmarital@qq.com
 */
@Service
public class PageService {
    @Autowired
    private BrandClient brandClient;
    @Autowired
    private CategoryClient categoryClient;
    @Autowired
    private GoodClient goodsClient;
    @Autowired
    private SpecificationClient specClient;

    public Map<String, Object> loadModel(Long id) {
        Map<String,Object> model = new HashMap<>();
        //查询spu
        Spu spu = goodsClient.querySpuById(id);
        //查询skus
        List<Sku> 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<Brand> brands = this.brandClient.queryBrandByIds(
                Arrays.asList(spu.getBrandId()));
        //查询商品分类
        List<Category> categories = categoryClient.queryCategoryByIds(
                Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
        //查询规格参数
        List<SpecGroup> specs = specClient.queryGroupByCid(spu.getCid3());
        //查询规格参数(附加)


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

        // 查询商品分类下的特有规格参数
        List<SpecParam> params =
                this.specClient.querySpecSpecParam(null, spu.getCid3(), null, false);
        // 处理成id:name格式的键值对
        Map<Long,String> 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<Map<String, Object>> allSpecs = JsonUtils
//                .nativeRead(allSpecJson, new TypeReference<List<Map<String, Object>>>() {});
//        Map<Integer,String> specName = new HashMap<>();
//        Map<Integer,Object> 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<String, Object> modelMap = this.goodsService.loadModel(id);
        // 放入模型
        model.addAllAttributes(modelMap);
        return "item";
    }
}

1.4.4.页面测试数据

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

<script th:inline="javascript">
    const a = /*[[${groups}]]*/ null;
    const b = /*[[${paramMap}]]*/ null;
    const c = /*[[${categories}]]*/ null;
    const d = /*[[${spu}]]*/ null;
    const e = /*[[${spuDetail}]]*/ null;
    const f = /*[[${skus}]]*/ null;
    const g = /*[[${brand}]]*/ null;
</script>

然后查看页面源码:

1529921980493

数据都成功查到了!

1.5.渲染面包屑

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

1526978423084

其数据有3部分:

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

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

<div class="crumb-wrap">
    <ul class="sui-breadcrumb">
        <li th:each="category : ${categories}">
            <a href="#" th:text="${category.name}">手机</a>
        </li>
        <li>
            <a href="#" th:text="${brand.name}">Apple</a>
        </li>
        <li class="active" th:text="${spu.title}">Apple iPhone 6s</li>
    </ul>
</div>

1.6.渲染商品列表

先看下整体效果:

1526979330657

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

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

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

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

1.6.1.副标题

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

在第87行左右:

<div class="news"><span th:utext="${spu.subTitle}"></span></div>

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

1526980061592

1.6.2.渲染规格属性列表

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

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

初始化数据

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

<script th:inline="javascript">
    // sku集合
        const skus = /*[[${skus}]]*/ [];
        const paramMap = /*[[${paramMap}]]*/ {};
        const  specialSpec= JSON.parse(/*[[${detail.specialSpec}]]*/ "");
</script>
  • specialSpec:这是SpuDetail中与唯一与Sku相关的数据

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

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

  • specialSpec:特有规格参数集合

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

1529923363960

通过Vue渲染

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

1529923450934

然后在页面中渲染:

<div id="specification" class="summary-wrap clearfix">
    <dl v-for="(v,k) in specialSpec" :key="k">
        <dt>
            <div class="fl title">
                <i v-text="paramMap[k]"></i>
            </div>
        </dt>
        <dd v-for="(o,j) in v" :key="j">
            <a href="javascript:;" class="selected">
                {{o}}<span  title="点击取消选择">&nbsp;</span>
            </a>
        </dd>
    </dl>
</div>

然后刷新页面查看:

1526983726820

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

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

1.6.3.规格属性的筛选

分析

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

1529923584730

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

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

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

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

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

1529923658242

然后在vue中保存:

1529923701283

页面改造

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

<div id="specification" class="summary-wrap clearfix">
    <dl v-for="(v,k) in specialSpec" :key="k">
        <dt>
            <div class="fl title">
                <i v-text="k"></i>
            </div>
        </dt>
        <dd v-for="(o,j) in v" :key="j" @click="indexes[k]=j">
            <a href="javascript:;" :class="{selected: j === indexes[k]}">
                {{o}}<span v-show="j === indexes[k]" title="点击取消选择">&nbsp;</span>
            </a>
        </dd>
    </dl>
</div>

效果:

1526984582539

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

1526984624633

1.6.4.确定SKU

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

1526984911652

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

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

1526984624633

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

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

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

在浏览器工具中查看:

1526985208770

1.6.5.渲染sku列表

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

图片列表

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

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

页面改造:

1526985757175

效果:

1526985783938

标题和价格

1526985959427

完整效果

1526986020278

1.7.商品详情

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

1526988361312

分成上下两部分:

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

1.7.2.商品详情

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

在页面的第420行左右:

<!--商品详情-->
<div class="intro-detail" th:utext="${detail.description}">
</div>

最终展示效果:

1526988524852

1.8.规格包装:

规格包装分成两部分:

  • 规格参数
  • 包装列表

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

1.8.1.规格参数

最终的效果:

1526995904991

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

1529924049003

分成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;
}

然后在页面渲染:

<div class="Ptable">
    <div class="Ptable-item" v-for="group in groups" :key="group.name">
        <h3>{{group.name}}</h3>
        <dl>
            <div v-for="p in group.params">
                <dt>{{p.name}}</dt><dd>{{p.v + (p.unit || '')}}</dd>
            </div>
        </dl>
    </div>
</div>

1.8.2.包装列表

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

<div class="package-list">
    <h3>包装清单</h3>
    <p th:text="${detail.packingList}"></p>
</div>

最终效果:

1526998348976

1526998483160

1.9.售后服务

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

<div id="three" class="tab-pane">
    <p>售后保障</p>
    <p th:text="${detail.afterService}"></p>
</div>

效果:

1526998635610

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值