037 商品详情01
1.
Thymeleaf的主要目标是为您的开发工作流程带来优雅的自然模板 - HTML。可以在直接浏览器中正确显示,并且可以作为静态原型,从而在开发团队中实现更强大的协作。
借助Spring Framework的模块,可以根据自己的喜好进行自由选择,可插拔功能组件,Thymeleaf是现代HTML5 JVM Web开发的理想选择 - 尽管它可以做的更多。
-
-
开箱即用:它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、改jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
-
多方言支持:Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
-
(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>lucky.leyou.parent</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <groupId>lucky.leyou.goods</groupId> <artifactId>leyou-goods-web</artifactId> <dependencies> <!--要给页面提供数据,要用到web--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--每一个独立的微服务都需要有eureka的启动器--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <!--本微服务需要调用其他微服务,需要用到feign--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <!--thymeleaf的启动器--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>lucky.leyou.item</groupId> <artifactId>leyou-item-interface</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <!--测试类的启动器--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <dependency> <groupId>lucky.leyou.common</groupId> <artifactId>leyou-common</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies> </project>
(3)
server:
port: 8084
spring:
application:
name: goods-web
thymeleaf:
cache: false
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
registry-fetch-interval-seconds: 5 #设置拉取微服务的时间
instance:
lease-renewal-interval-in-seconds: 5 # 每隔5秒发送一次心跳
lease-expiration-duration-in-seconds: 10 # 10秒不发送就过期
(4)编写启动类
package lucky.leyou; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication //入口类Application的启动注解 @EnableDiscoveryClient //能够让注册中心能够发现,扫描到该微服务 @EnableFeignClients // 开启feign客户端 public class LeyouGoodsWebApplication { public static void main(String[] args) { SpringApplication.run(LeyouGoodsWebApplication.class, args); } }
(5)页面模板
我们从leyou-portal中复制item.html模板到当前项目resource目录下的templates中。
修改html:引入thymeleaf
<html lang="en" xmlns:th="http://www.thymeleaf.org">
初期模块结构图:
3.
那么问题来了:商品详情页是一个SKU?还是多个SKU的集合?
所以,页面跳转时,我们应该携带SPU的id信息。
例如:http://www.leyou.com/item/2314123.html
这里就采用了路径占位符的方式来传递spu的id,我们打开search.html
<div class="p-img"> <!--a标签内放置了商品的大图,并绑定了跳转的链接--> <!--需要动态渲染,用:href来替换原来的href--> <!--goods.id为spuid 查看后台search微服务的domain goods类可知--> <a :href="'item/'+goods.id+'.html'" target="_blank"><img :src="goods.selected.image" height="200"/></a> <ul class="skus"> <!--若sku的id等于goods.selected选中的id,则去渲染这个样式,@mouseOver鼠标移动事件--> <li :class="{selected: goods.selected.id==sku.id}" v-for="(sku,j) in goods.skus" @mouseOver="goods.selected=sku"><img :src="sku.image"></li> </ul> </div>
刷新页面后再看:
(2)
package lucky.leyou.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("item") public class GoodsController { /** * 跳转到商品详情页 * @param model 利用model传递数据到前端工程 * @param id * @return */ @GetMapping("{id}.html") public String toItemPage(Model model, @PathVariable("id")Long id){ return "item"; //返回视图名称 } }
(3)nginx反向代理
gzip on; server { listen 80; server_name www.leyou.com; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; location /item { proxy_pass http://127.0.0.1:8084; proxy_connect_timeout 600; proxy_read_timeout 600; } location / { proxy_pass http://127.0.0.1:9002; proxy_connect_timeout 600; proxy_read_timeout 600; } }
配置代码说明:
把以/item开头的请求,代理到我们的8084端口。
重启Nginx
nginx -s reload
(4)测试
(5)逻辑分析图
4.封装数据模型
我们已知的条件是传递来的spu的id,我们需要根据spu的id查询到下面的数据:
-
spu信息
-
spu的详情
-
spu下的所有sku
-
品牌
-
商品三级分类
-
商品规格参数、规格参数组
(1)
/** * 根据spuid查询spu * @param id spuid * @return */ @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); }
IGoodsService及GoodsServiceImpl
/** * 根据spuid查询spu * @param id spuid * @return */ @Override public Spu querySpuById(Long id) { return this.spuMapper.selectByPrimaryKey(id); }
GoodsApi:
/** * 根据spu的id查询spu * @param id spuid * @return */ @GetMapping("spu/{id}") public Spu querySpuById(@PathVariable("id") Long id);
<2>查询规格参数组
我们在页面展示规格时,需要按组展示:
组内有多个参数,为了方便展示。我们在leyou-item-service中提供一个接口,查询规格组,同时在规格组内的所有参数。
SpecificationController:
/** * 根据分类id查询规格参数 * @param cid * @return */ @GetMapping("{cid}") public ResponseEntity<List<SpecGroup>> querySpecsByCid(@PathVariable("cid") Long cid){ List<SpecGroup> list = this.specificationService.querySpecsByCid(cid); if(list == null || list.size() == 0){ return new ResponseEntity<>(HttpStatus.NOT_FOUND); } return ResponseEntity.ok(list); }
SpecificationServiceImpl:
/** * 根据分类id查询规格参数 * @param cid * @return */ @Override public List<SpecGroup> querySpecsByCid(Long cid) { // 根据分类id查询分组,查询规格组 List<SpecGroup> groups = this.queryGroupsByCid(cid); groups.forEach(g -> { // 查询组内参数 g.setParams(this.queryParams(g.getId(), null, null, null)); }); return groups; }
SpecificationAPI:
package lucky.leyou.item.api; import lucky.leyou.item.domain.SpecGroup; import lucky.leyou.item.domain.SpecParam; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.List; /** * 规格参数的接口:供feign使用 */ @RequestMapping("spec") public interface SpecificationApi { @GetMapping("params") public List<SpecParam> queryParams( @RequestParam(value = "gid", required = false) Long gid, @RequestParam(value = "cid", required = false) Long cid, @RequestParam(value = "generic", required = false) Boolean generic, @RequestParam(value = "searching", required = false) Boolean searching ); // 查询规格参数组,及组内参数 @GetMapping("{cid}") List<SpecGroup> querySpecsByCid(@PathVariable("cid") Long cid); @GetMapping("groups/{cid}") public List<SpecGroup> querySpecGroups(@PathVariable("cid") Long cid); }
(2)
(3)
这里要查询的数据:
-
SPU
-
SpuDetail
-
SKU集合
-
商品分类
-
这里值需要分类的id和name就够了,因此我们查询到以后自己需要封装数据
-
-
品牌对象
-
规格组
-
查询规格组的时候,把规格组下所有的参数也一并查出,上面提供的接口中已经实现该功能,我们直接调
-
-
sku的特有规格参数
有了规格组,为什么这里还要查询?
但是,在页面渲染时,需要知道参数的名称,如图:
我们就需要把id和name一一对应起来,因此需要额外查询sku的特有规格参数,然后变成一个id:name的键值对格式。也就是一个Map,方便将来根据id查找!
<1>Service代码
package lucky.leyou.service; import lucky.leyou.client.BrandClient; import lucky.leyou.client.CategoryClient; import lucky.leyou.client.GoodsClient; import lucky.leyou.client.SpecificationClient; import lucky.leyou.item.domain.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.*; @Service public class GoodsService { @Autowired private BrandClient brandClient; @Autowired private CategoryClient categoryClient; @Autowired private GoodsClient goodsClient; @Autowired private SpecificationClient specificationClient; public Map<String, Object> loadData(Long spuId){ Map<String, Object> map = new HashMap<>(); // 根据id查询spu对象 Spu spu = this.goodsClient.querySpuById(spuId); // 根据spuid查询spudetail SpuDetail spuDetail = this.goodsClient.querySpuDetailById(spuId); // 查询sku集合 List<Sku> skus = this.goodsClient.querySkuBySpuId(spuId); // 查询分类 List<Long> cids = Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()); List<String> names = this.categoryClient.queryNameByIds(cids); List<Map<String, Object>> categories = new ArrayList<>(); for (int i = 0; i < cids.size(); i++) { Map<String, Object> categoryMap = new HashMap<>(); categoryMap.put("id", cids.get(i)); categoryMap.put("name", names.get(i)); categories.add(categoryMap); } // 查询品牌 Brand brand = this.brandClient.queryBrandById(spu.getBrandId()); // 查询规格参数组 List<SpecGroup> groups = this.specificationClient.querySpecsByCid(spu.getCid3()); // 查询特殊的规格参数 List<SpecParam> params = this.specificationClient.queryParams(null, spu.getCid3(), null, false); Map<Long, String> paramMap = new HashMap<>(); params.forEach(param -> { paramMap.put(param.getId(), param.getName()); }); // 封装spu map.put("spu", spu); // 封装spuDetail map.put("spuDetail", spuDetail); // 封装sku集合 map.put("skus", skus); // 分类 map.put("categories", categories); // 品牌 map.put("brand", brand); // 规格参数组 map.put("groups", groups); // 查询特殊规格参数 map.put("paramMap", paramMap); return map; } }
<2>然后在controller中把数据放入model:
package lucky.leyou.controller; import lucky.leyou.service.GoodsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import java.util.Map; @Controller @RequestMapping("item") public class GoodsController { @Autowired private GoodsService goodsService; /** * 跳转到商品详情页 * @param model 利用model传递数据到前端工程 * @param id * @return */ @GetMapping("{id}.html") public String toItemPage(Model model, @PathVariable("id")Long id){ // 加载所需的数据 Map<String, Object> modelMap = this.goodsService.loadData(id); // 放入模型 model.addAllAttributes(modelMap); return "item"; //返回视图名称 } }
(4)
<script th:inline="javascript"> const a = /*[[${groups}]]*/ []; const b = /*[[${params}]]*/ []; const c = /*[[${categories}]]*/ []; const d = /*[[${spu}]]*/ {}; const e = /*[[${spuDetail}]]*/ {}; const f = /*[[${skus}]]*/ []; const g = /*[[${brand}]]*/ {}; </script>
然后查看页面源码:
5.渲染面包屑
在商品展示页的顶部,有一个商品分类、品牌、标题的面包屑
-
商品分类
-
商品品牌
-
spu标题
<!--面包屑部分--> <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>
ctrl+shift+f9 刷新leyou-goods-web模块中的templates下的html页面
浏览器中刷新页面进行测试:
6.
先看下整体效果:
-
sku图片
-
sku标题
-
副标题
-
sku价格
-
特有规格属性列表
其中,sku 的图片、标题、价格,都必须在用户选中一个具体sku后,才能渲染。而特有规格属性列表可以在spuDetail中查询到。而副标题则是在spu中,直接可以在页面渲染
(1)副标题
<div class="news" th:utext="${spu.subTitle}"><span>推荐选择下方[移动优惠购],手机套餐齐搞定,不用换号,每月还有花费返</span></div>
Navicat打开数据库表:
(2)
<script th:inline="javascript"> // sku集合 const skus = /*[[${skus}]]*/ []; // 规格参数id与name对 const paramMap = /*[[${params}]]*/ {}; // 特有规格参数集合 const specialSpec = JSON.parse(/*[[${spuDetail.specialSpec}]]*/ ""); </script>
-
因此我们并没有保存整个spuDetail,而是只保留了这个属性,而且需要手动转为js对象。
-
paramMap:规格参数的id和name键值对,方便页面根据id获取参数名
-
skus:sku集合
<2>
<div id="specification" class="summary-wrap clearfix"> <dl v-for="(v,k) in specialSpec" :key="k"> <dt> <div class="fl title"> <i>{{paramMap[k]}}</i> </div> </dt> <dd v-for="(str,j) in v" :key="j"> <a href="javascript:;" class="selected"> {{str}}<span title="点击取消选择"> </span> </a> </dd> </dl> </div>
然后刷新页面查看:
{
"4":0,
"12":0,
"13":0
}
我们在head
然后在vue中保存:
我们在页面中,通过判断indexes的值来判断当前规格是否被选中,并且给规格绑定点击事件,点击规格项后,修改indexes中的对应值:
<div id="specification" class="summary-wrap clearfix"> <dl v-for="(v,k) in specialSpec" :key="k"> <dt> <div class="fl title"> <i>{{paramMap[k]}}</i> </div> </dt> <dd v-for="(str,j) in v" :key="j"> <a href="javascript:;" :class="{selected: j===indexes[k]}" @click="indexes[k]=j"> {{str}}<span v-if="j===indexes[k]" title="点击取消选择"> </span> </a> </dd> </dl> </div>
效果图:
(4)
我们在vue中定义一个计算属性
computed:{
sku(){
const index = Object.values(this.indexes).join("_");
return this.skus.find(s => s.indexes == index);
}
}
在浏览器工具中查看:
(5)
<2>
computed: {
sku(){
const index = Object.values(this.indexes).join("_");
return this.skus.find(s=>s.indexes==index);
},
images(){
return this.sku.images ? this.sku.images.split(",") : [''];
}
},
页面改造:
<div class="zoom"> <!--默认第一个预览--> <div id="preview" class="spec-preview"> <span class="jqzoom"> <img :jqimg="images[0]" :src="images[0]" width="400px" height="400px"/> </span> </div> <!--下方的缩略图--> <div class="spec-scroll"> <a class="prev"><</a> <!--左右按钮--> <div class="items"> <ul> <li v-for="(image, i) in images" :key="i"> <img :src="image" :bimg="image" onmousemove="preview(this)" /> </li> </ul> </div> <a class="next">></a> </div> </div>
最终效果图:
7.
<!--商品详情--> <div class="intro-detail" th:utext="${spuDetail.description}"> </div>
最终展示效果:
8.
-
规格参数
-
包装列表
后台传给template包下的item.html页面的model中有一个groups
从spuDetail中取出genericSpec并取出groups:
<script th:inline="javascript"> // sku集合 const skus = /*[[${skus}]]*/ []; // 规格参数id与name对 const paramMap = /*[[${paramMap}]]*/ {}; // 特有规格参数集合,JSON.parse,可将json字符串转换为json对象 const specialSpec = JSON.parse(/*[[${spuDetail.specialSpec}]]*/ ""); const genericSpec = JSON.parse(/*[[${spuDetail.genericSpec}]]*/ ""); let groups= /*[[${groups}]]*/ []; //创建一个对象来保存用户选择的索引,并设置每一个key值对应的默认值为0 const indexes={}; Object.keys(paramMap).forEach(param=>indexes[param]=0); </script>
把genericSpec引入到Vue实例:
因为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>
(2)
包装列表在商品详情中,我们一开始并没有赋值到Vue实例中,但是可以通过Thymeleaf来渲染
<div class="package-list"> <h3>包装清单</h3> <p th:text="${spuDetail.packingList}"></p> </div>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)