乐优商城学习Day09:
注意:此次代码都是在第八天的基础上
第八天的链接如下:
https://blog.csdn.net/zcylxzyh/article/details/100859210
此次笔记内容主要为:
1、了解thymeleaf
2、商品详情页的实现(后台)
3、页面静态化
4、虚拟机安装Rabbitmq
下面开始第九天的学习:
1、了解thymeleaf
1.1 thymeleaf简介
官方网站:https://www.thymeleaf.org/index.html
Thymeleaf是用来开发Web和独立环境项目的现代服务器端Java模板引擎。
Thymeleaf的主要目标是为您的开发工作流程带来优雅的自然模板 - HTML。可以在直接浏览器中正确显示,并且可以作为静态原型,从而在开发团队中实现更强大的协作。
借助Spring Framework的模块,可以根据自己的喜好进行自由选择,可插拔功能组件,Thymeleaf是现代HTML5 JVM Web开发的理想选择 - 尽管它可以做的更多。
Spring官方支持的服务的渲染模板中,并不包含jsp。而是Thymeleaf和Freemarker等,而Thymeleaf与SpringMVC的视图技术,及SpringBoot的自动化配置集成非常完美,几乎没有任何成本,你只用关注Thymeleaf的语法即可。
特点:
- 动静结合:Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
- 开箱即用:它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
- 多方言支持:Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
- 与SpringBoot完美整合,SpringBoot提供了Thymeleaf的默认配置,并且为Thymeleaf设置了视图解析器,我们可以像以前操作jsp一样来操作Thymeleaf。代码几乎没有任何区别,就是在模板语法上有区别。
1.2 thymeleaf快速入门
这里为了方便就直接把thymeleaf入门案例在商品详情微服务中写啦
创建微服务:
配置文件:(注:这里的配置文件是商品微服务的配置文件)
server:
port: 8084
spring:
application:
name: page-service
thymeleaf:
cache: false
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
创建目录:templates
名字一定要是这个templates,他会自动取这里目录里面找页面
这个代表了前缀后缀,classpath意味着在java或者resources中
创建hello.html和HelloController、User以及启动类:(SpringBoot 任何项目要想启动就需要有启动类)
LyPageApplication 启动类代码:
package com.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
@EnableDiscoveryClient
@EnableFeignClients
public class LyPageApplication {
public static void main(String[] args) {
SpringApplication.run(LyPageApplication.class);
}
}
HelloController:
package com.leyou.page.web;
import com.leyou.page.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HelloController {
@GetMapping("hello")
public String toHello(Model model){
User user = new User();
user.setAge(21);
user.setName("Jack Chen");
user.setFriend(new User("李小龙", 30,null));
model.addAttribute("user", user);
//普通字符串被当成视图名称,结合前缀和后缀寻找视图
return "hello";
}
}
显示提示:xmlns:th=“http://www.thymeleaf.org”
hello代码:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>hello</title>
</head>
<body>
<h1>
欢迎您:<span th:text="${user.name}"></span>
</h1>
</body>
</html>
User:
package com.leyou.page.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
String name;
int age;
User friend;// 对象类型属性
}
在IDEA中需要重新加载文件:
1.3 Thymeleaf 语法(含有对1.2的解释)
Thymeleaf的主要作用是把model中的数据渲染到html中,因此其语法主要是如何解析model中的数据。从以下方面来学习:
- 变量
- 方法
- 条件判断
- 循环
- 运算
- 逻辑运算
- 布尔运算
- 比较运算
- 条件运算
- 其它
4.1.变量
变量案例
我们先新建一个实体类:User
public class User {
String name;
int age;
User friend;// 对象类型属性
}
然后在模型中添加数据
@GetMapping("show2")
public String show2(Model model){
User user = new User();
user.setAge(21);
user.setName("Jack Chen");
user.setFriend(new User("李小龙", 30));
model.addAttribute("user", user);
return "show2";
}
语法说明:
Thymeleaf通过${}来获取model中的变量,注意这不是el表达式,而是ognl表达式,但是语法非常像。
示例:
我们在页面获取user数据:
<h1>
欢迎您:<span th:text="${user.name}">请登录</span>
</h1>
效果:
感觉跟el表达式几乎是一样的。不过区别在于,我们的表达式写在一个名为:th:text的标签属性中,这个叫做指令
动静结合
指令:
Thymeleaf崇尚自然模板,意思就是模板是纯正的html代码,脱离模板引擎,在纯静态环境也可以直接运行。现在如果我们直接在html中编写 ${}这样的表达式,显然在静态环境下就会出错,这不符合Thymeleaf的理念。
Thymeleaf中所有的表达式都需要写在指令中,指令是HTML5中的自定义属性,在Thymeleaf中所有指令都是以th:开头。因为表达式${user.name}是写在自定义属性中,因此在静态环境下,表达式的内容会被当做是普通字符串,浏览器会自动忽略这些指令,这样就不会报错了!
现在,我们不经过SpringMVC,而是直接用浏览器打开页面看看:
- 静态页面中,th指令不被识别,但是浏览器也不会报错,把它当做一个普通属性处理。这样span的默认值请登录就会展现在页面
- 如果是在Thymeleaf环境下,th指令就会被识别和解析,而th:text的含义就是替换所在标签中的文本内容,于是user.name的值就替代了 span中默认的请登录
指令的设计,正是Thymeleaf的高明之处,也是它优于其它模板引擎的原因。动静结合的设计,使得无论是前端开发人员还是后端开发人员可以完美契合。
向下兼容
但是要注意,如果浏览器不支持Html5怎么办?
如果不支持这种th:的命名空间写法,那么可以把th:text换成 data-th-text,Thymeleaf也可以兼容。
escape
另外,th:text指令出于安全考虑,会把表达式读取到的值进行处理,防止html的注入。
例如,
你好
将会被格式化输出为 l t ; p lt;p lt;pgt;你好 l t ; / p lt;/p lt;/plt;。如果想要不进行格式化输出,而是要输出原始内容,则使用th:utext来代替.
ognl表达式的语法糖
刚才获取变量值,我们使用的是经典的对象.属性名方式。但有些情况下,我们的属性名可能本身也是变量,怎么办?
ognl提供了类似js的语法方式:
例如: u s e r . n a m e 可 以 写 作 {user.name} 可以写作 user.name可以写作{user[‘name’]}
4.2.自定义变量
场景
看下面的案例:
<h2>
<p>Name: <span th:text="${user.name}">Jack</span>.</p>
<p>Age: <span th:text="${user.age}">21</span>.</p>
<p>friend: <span th:text="${user.friend.name}">Rose</span>.</p>
</h2>
我们获取用户的所有信息,分别展示。
当数据量比较多的时候,频繁的写user.就会非常麻烦。
因此,Thymeleaf提供了自定义变量来解决:
示例:
<h2 th:object="${user}">
<p>Name: <span th:text="*{name}">Jack</span>.</p>
<p>Age: <span th:text="*{age}">21</span>.</p>
<p>friend: <span th:text="*{friend.name}">Rose</span>.</p>
</h2>
- 首先在 h2上 用 th:object="${user}"获取user的值,并且保存
- 然后,在h2内部的任意元素上,可以通过 *{属性名}的方式,来获取user中的属性,这样就省去了大量的user.前缀了
方法
ognl表达式中的方法调用
ognl表达式本身就支持方法调用,例如:
<h2 th:object="${user}">
<p>FirstName: <span th:text="*{name.split(' ')[0]}">Jack</span>.</p>
<p>LastName: <span th:text="*{name.split(' ')[1]}">Li</span>.</p>
</h2>
- 这里我们调用了name(是一个字符串)的split方法。
Thymeleaf内置对象
Thymeleaf中提供了一些内置对象,并且在这些对象中提供了一些方法,方便我们来调用。获取这些对象,需要使用#对象名来引用。
- 一些环境相关对象
对象 | 作用 |
---|---|
#ctx | 获取Thymeleaf自己的Context对象 |
#requset | 如果是web程序,可以获取HttpServletRequest对象 |
#response | 如果是web程序,可以获取HttpServletReponse对象 |
#session | 如果是web程序,可以获取HttpSession对象 |
#servletContext | 如果是web程序,可以获取HttpServletContext对象 |
- Thymeleaf提供的全局对象:
对象 | 作用 |
---|---|
#dates | 处理java.util.date的工具对象 |
#calendars | 处理java.util.calendar的工具对象 |
#numbers | 用来对数字格式化的方法 |
#strings | 用来处理字符串的方法 |
#bools | 用来判断布尔值的方法 |
#arrays | 用来护理数组的方法 |
#lists | 用来处理List集合的方法 |
#sets | 用来处理set集合的方法 |
#maps | 用来处理map集合的方法 |
- 举例
我们在环境变量中添加日期类型对象
@GetMapping("show3") public String show3(Model model){ model.addAttribute("today", new Date()); return "show3"; }
在页面中处理
<p> 今天是: <span th:text="${#dates.format(today,'yyyy-MM-dd')}">2018-04-25</span> </p>
效果:
字面值
有的时候,我们需要在指令中填写基本类型如:字符串、数值、布尔等,并不希望被Thymeleaf解析为变量,这个时候称为字面值。
-
字符串字面值
使用一对’引用的内容就是字符串字面值了:
<p> 你正在观看 <span th:text="'thymeleaf'">template</span> 的字符串常量值. </p>
th:text中的thymeleaf并不会被认为是变量,而是一个字符串
-
数字字面值
数字不需要任何特殊语法, 写的什么就是什么,而且可以直接进行算术运算
<p>今年是 <span th:text="2018">1900</span>.</p>
<p>两年后将会是 <span th:text="2018 + 2">1902</span>.</p>
-
布尔字面值
布尔类型的字面值是true或false:
<div th:if="true"> 你填的是true </div>
这里引用了一个th:if指令,跟vue中的v-if类似
4.5 拼接
我们经常会用到普通字符串与表达式拼接的情况:
<span th:text="'欢迎您:' + ${user.name} + '!'"></span>
字符串字面值需要用’’,拼接起来非常麻烦,Thymeleaf对此进行了简化,使用一对|即可:
<span th:text="|欢迎您:${user.name}|"></span>
与上面是完全等效的,这样就省去了字符串字面值的书写。
运算
需要注意: 内 部 的 是 通 过 O G N L 表 达 式 引 擎 解 析 的 , 外 部 的 才 是 通 过 T h y m e l e a f 的 引 擎 解 析 , 因 此 运 算 符 尽 量 放 在 {}内部的是通过OGNL表达式引擎解析的,外部的才是通过Thymeleaf的引擎解析,因此运算符尽量放在 内部的是通过OGNL表达式引擎解析的,外部的才是通过Thymeleaf的引擎解析,因此运算符尽量放在{}外进行。
-
算术运算
支持的算术运算符:+ - * / %<span th:text="${user.age}"></span> <span th:text="${user.age}%2 == 0"></span>
-
比较运算
支持的比较运算:>, <, >= and <= ,但是>, <不能直接使用,因为xml会解析为标签,要使用别名。
注意 == and !=不仅可以比较数值,类似于equals的功能。
可以使用的别名:gt (>), lt (<), ge (>=), le (<=), not (!). Also eq (==), neq/ne (!=). -
条件运算
-
三元运算
<span th:text="${user.sex} ? '男':'女'"></span>
三元运算符的三个部分:conditon ? then : else
condition:条件
then:条件成立的结果
else:不成立的结果
其中的每一个部分都可以是Thymeleaf中的任意表达式。
- 默认值
有的时候,我们取一个值可能为空,这个时候需要做非空判断,可以使用 表达式 ?: 默认值简写:
<span th:text="${user.name} ?: '二狗'"></span>
当前面的表达式值为null时,就会使用后面的默认值。
注意:?:
之间没有空格。
-
循环
循环也是非常频繁使用的需求,我们使用th:each指令来完成:
假如有用户的集合:users在Context中。
<tr th:each="user : ${users}">
<td th:text="${user.name}">Onions</td>
<td th:text="${user.age}">2.41</td>
</tr>
- ${users} 是要遍历的集合,可以是以下类型:
- Iterable,实现了Iterable接口的类
- Enumeration,枚举
- Interator,迭代器
- Map,遍历得到的是Map.Entry
- Array,数组及其它一切符合数组结果的对象
在迭代的同时,我们也可以获取迭代的状态对象:
<tr th:each="user,stat : ${users}">
<td th:text="${user.name}">Onions</td>
<td th:text="${user.age}">2.41</td>
</tr>
stat对象包含以下属性:
- index,从0开始的角标
- count,元素的个数,从1开始
- size,总元素个数
- current,当前遍历到的元素
- even/odd,返回是否为奇偶,boolean值
- first/last,返回是否为第一或最后,boolean值
逻辑判断
有了if和else,我们能实现一切功能_。
Thymeleaf中使用th:if 或者 th:unless ,两者的意思恰好相反。
<span th:if="${user.age} < 24">小鲜肉</span>
如果表达式的值为true,则标签会渲染到页面,否则不进行渲染。
以下情况被认定为true:
- 表达式值为true
- 表达式值为非0数值
- 表达式值为非0字符
- 表达式值为字符串,但不是"false",“no”,“off”
- 表达式不是布尔、字符串、数字、字符中的任何一种
其它情况包括null都被认定为false
4.9 分支控制switch
这里要使用两个指令:th:switch 和 th:case
<div th:switch="${user.role}">
<p th:case="'admin'">用户是管理员</p>
<p th:case="'manager'">用户是经理</p>
<p th:case="*">用户是别的玩意</p>
</div>
需要注意的是,一旦有一个th:case成立,其它的则不再判断。与java中的switch是一样的。
另外th:case="*"表示默认,放最后。
页面:
JS模板
模板引擎不仅可以渲染html,也可以对JS中的进行预处理。而且为了在纯静态环境下可以运行,其Thymeleaf代码可以被注释起来:
<script th:inline="javascript">
const user = /*[[${user}]]*/ {};
const age = /*[[${user.age}]]*/ 20;
console.log(user);
console.log(age)
</script>
- 在script标签中通过th:inline="javascript"来声明这是要特殊处理的js脚本
- 语法结构:
const user = /*[[Thymeleaf表达式]]*/ "静态环境下的默认值";
因为Thymeleaf被注释起来,因此即便是静态环境下, js代码也不会报错,而是采用表达式后面跟着的默认值。
看看页面的源码:
我们的User对象被直接处理为json格式了,非常方便。
控制台:
第一部分结束。
2、商品详情页的实现(后台)
我们在ly-page中完成商品详情页的实现。
启动类,配置文件,还有pom文件为上面所示。
导入item.html页面导入到项目中:
item.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE">
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"/>
<title>乐优商城--商品详情页</title>
<link rel="icon" href="/assets/img/favicon.ico">
<link rel="stylesheet" type="text/css" href="/css/webbase.css"/>
<link rel="stylesheet" type="text/css" href="/css/pages-item.css"/>
<link rel="stylesheet" type="text/css" href="/css/pages-zoom.css"/>
<link rel="stylesheet" type="text/css" href="/css/widget-cartPanelView.css"/>
<style type="text/css">
.goods-intro-list li {
display: inline-block;
width: 300px;
}
.Ptable {
margin: 10px 0;
}
.Ptable-item {
padding: 12px 0;
line-height: 220%;
color: #999;
font-size: 12px;
border-bottom: 1px solid #eee;
}
.Ptable-item h3 {
width: 110px;
text-align: right;
}
.Ptable-item h3, .package-list h3 {
font-weight: 400;
font-size: 12px;
float: left;
}
h3 {
display: block;
font-size: 1.17em;
-webkit-margin-before: 1em;
-webkit-margin-after: 1em;
-webkit-margin-start: 0px;
-webkit-margin-end: 0px;
font-weight: bold;
}
.Ptable-item dl {
margin-left: 110px;
}
dl {
display: block;
-webkit-margin-before: 1em;
-webkit-margin-after: 1em;
-webkit-margin-start: 0px;
-webkit-margin-end: 0px;
}
.Ptable-item dt {
width: 160px;
float: left;
text-align: right;
padding-right: 5px;
}
.Ptable-item dd {
margin-left: 210px;
}
dd {
display: block;
-webkit-margin-start: 40px;
}
.package-list {
padding: 12px 0;
line-height: 220%;
color: #999;
font-size: 12px;
margin-top: -1px;
}
.package-list h3 {
width: 130px;
text-align: right;
}
.package-list p {
margin-left: 155px;
padding-right: 50px;
}
</style>
</head>
<body>
<!-- 头部栏位 -->
<!--页面顶部,由js动态加载-->
<div id="itemApp">
<div id="nav-bottom">
<ly-top/>
</div>
<div class="py-container">
<div id="item">
<div class="crumb-wrap">
<ul class="sui-breadcrumb">
<li th:each="c : ${categories}">
<a href="#" th:text="${c.name}">手机</a>
</li>
<li>
<a href="#" th:text="${brand.name}">Apple</a>
</li>
<li class="active" th:text="${title}">Apple iPhone 6s</li>
</ul>
</div>
<!--product-info-->
<div class="product-info">
<div class="fl preview-wrap">
<!--放大镜效果-->
<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="img in images">
<img :src="img" :bimg="img" onmousemove="preview(this)"/>
</li>
</ul>
</div>
<a class="next">></a>
</div>
</div>
</div>
<div class="fr itemInfo-wrap">
<div class="sku-name">
<h4 v-text="sku.title"></h4>
</div>
<div class="news"><span th:utext="${subTitle}">Apple iPhone 6s 4GB 128GB 土豪金</span></div>
<div class="summary">
<div class="summary-wrap">
<div class="fl title"><i>价 格</i></div>
<div class="fl price">
<i>¥</i><em v-text="ly.formatPrice(sku.price)"></em><span>降价通知</span>
</div>
<div class="fr remark"><i>累计评价</i><em>612188</em></div>
</div>
<div class="summary-wrap">
<div class="fl title">
<i>促 销</i>
</div>
<div class="fl fix-width">
<i class="red-bg">加价购</i>
<em class="t-gray">满999.00另加20.00元,或满1999.00另加30.00元,或满2999.00另加40.00元,即可在购物车换
购热销商品</em>
</div>
</div>
</div>
<div class="support">
<div class="summary-wrap">
<div class="fl title">
<i>支 持</i>
</div>
<div class="fl fix-width">
<em class="t-gray">以旧换新,闲置手机回收 4G套餐超值抢 礼品购</em>
</div>
</div>
<div class="summary-wrap">
<div class="fl title">
<i>配 送 至</i>
</div>
<div class="fl fix-width">
<em class="t-gray">上海 <span v-text="sku.stock > 0 ? '有货' : '缺货'"></span></em>
</div>
</div>
</div>
<div class="clearfix choose">
<div id="specification" class="summary-wrap clearfix">
<dl v-for="(options,id) in specialSpec" :key="id">
<dt>
<div class="fl title">
<i v-text="params[id]"></i>
</div>
</dt>
<dd v-for="(o,i) in options" :key="i" @click="selectSku(id,i)">
<a href="javascript:;" :class="{selected:i === indexes[id], locked:locked(id, i)}">
{
{o}}<span title="点击取消选择"> </span>
</a>
</dd>
</dl>
</div>
<div class="summary-wrap">
<div class="fl title">
<div class="control-group">
<div class="controls">
<input autocomplete="off" type="text" disabled v-model="num" minnum="1"
class="itxt"/>
<a href="javascript:void(0)" class="increment plus" @click="increment">+</a>
<a href="javascript:void(0)" class="increment mins" @click="decrement">-</a>
</div>
</div>
</div>
<div class="fl">
<ul class="btn-choose unstyled">
<li>
<a href="#" @click.prevent="addCart" target="_blank"
class="sui-btn btn-danger addshopcar">加入购物车</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<!--product-detail-->
<div class="clearfix product-detail">
<div class="fl aside">
<ul class="sui-nav nav-tabs tab-wraped">
<li class="active">
<a href="#index" data-toggle="tab">
<span>相关分类</span>
</a>
</li>
<li>
<a href="#profile" data-toggle="tab">
<span>推荐品牌</span>
</a>
</li>
</ul>
<div class="tab-content tab-wraped">
<div id="index" class="tab-pane active">
<ul class="part-list unstyled">
<li>手机</li>
<li>手机壳</li>
<li>内存卡</li>
<li>Iphone配件</li>
<li>贴膜</li>
<li>手机耳机</li>
<li>移动电源</li>
<li>平板电脑</li>
</ul>
<ul class="goods-list unstyled">
<li>
<div class="list-wrap">
<div class="p-img">
<img src="/img/_/part01.png"/>
</div>
<div class="attr">
<em>Apple苹果iPhone 6s (A1699)</em>
</div>
<div class="price">
<strong>
<em>¥</em>
<i>6088.00</i>
</strong>
</div>
<div class="operate">
<a href="javascript:void(0);" class="sui-btn btn-bordered">加入购物车</a>
</div>
</div>
</li>
<li>
<div class="list-wrap">
<div class="p-img">
<img src="/img/_/part02.png"/>
</div>
<div class="attr">
<em>Apple苹果iPhone 6s (A1699)</em>
</div>
<div class="price">
<strong>
<em>¥</em>
<i>6088.00</i>
</strong>
</div>
<div class="operate">
<a href="javascript:void(0);" class="sui-btn btn-bordered">加入购物车</a>
</div>
</div>
</li>
<li>
<div class="list-wrap">
<div class="p-img">
<img src="/img/_/part03.png"/>
</div>
<div class="attr">
<em>Apple苹果iPhone 6s (A1699)</em>
</div>
<div class="price">
<strong>
<em>¥</em>
<i>6088.00</i>
</strong>
</div>
<div class="operate">
<a href="javascript:void(0);" class="sui-btn btn-bordered">加入购物车</a>
</div>
</div>
<div class="list-wrap">
<div class="p-img">
<img src="/img/_/part02.png"/>
</div>
<div class="attr">
<em>Apple苹果iPhone 6s (A1699)</em>
</div>
<div class="price">
<strong>
<em>¥</em>
<i>6088.00</i>
</strong>
</div>
<div class="operate">
<a href="javascript:void(0);" class="sui-btn btn-bordered">加入购物车</a>
</div>
</div>
<div class="list-wrap">
<div class="p-img">
<img src="/img/_/part03.png"/>
</div>
<div class="attr">
<em>Apple苹果iPhone 6s (A1699)</em>
</div>
<div class="price">
<strong>
<em>¥</em>
<i>6088.00</i>
</strong>
</div>
<div class="operate">
<a href="javascript:void(0);" class="sui-btn btn-bordered">加入购物车</a>
</div>
</div>
</li>
</ul>
</div>
<div id="profile" class="tab-pane">
<p>推荐品牌</p>
</div>
</div>
</div>
<div class="fr detail">
<div class="clearfix fitting">
<h4 class="kt">选择搭配</h4>
<div class="good-suits">
<div class="fl master">
<div class="list-wrap">
<div class="p-img">
<img src="/img/_/l-m01.png"/>
</div>
<em>¥5299</em>
<i>+</i>
</div>
</div>
<div class="fl suits">
<ul class="suit-list">
<li class="">
<div id="e">
<img src="/img/_/dp01.png"/>
</div>
<i>Feless费勒斯VR</i>
<label data-toggle="checkbox" class="checkbox-pretty">
<input type="checkbox"><span>39</span>
</label>
</li>
<li class="">
<div id=""><img src="/img/_/dp02.png"/></div>
<i>Feless费勒斯VR</i>
<label data-toggle="checkbox" class="checkbox-pretty">
<input type="checkbox"><span>50</span>
</label>
</li>
<li class="">
<div id=""><img src="/img/_/dp03.png"/></div>
<i>Feless费勒斯VR</i>
<label data-toggle="checkbox" class="checkbox-pretty">
<input type="checkbox"><span>59</span>
</label>
</li>
<li class="">
<div id=""><img src="/img/_/dp04.png"/></div>
<i>Feless费勒斯VR</i>
<label data-toggle="checkbox" class="checkbox-pretty">
<input type="checkbox"><span>99</span>
</label>
</li>
</ul>
</div>
<div class="fr result">
<div class="num">已选购0件商品</div>
<div class="price-tit"><strong>套餐价</strong></div>
<div class="price">¥5299</div>
<button class="sui-btn btn-danger addshopcar">加入购物车</button>
</div>
</div>
</div>
<div class="tab-main intro">
<ul class="sui-nav nav-tabs tab-wraped">
<li class="active">
<a href="#one" data-toggle="tab">
<span>商品介绍</span>
</a>
</li>
<li>
<a href="#two" data-toggle="tab">
<span>规格与包装</span>
</a>
</li>
<li>
<a href="#three" data-toggle="tab">
<span>售后保障</span>
</a>
</li>
<li>
<a href="#four" data-toggle="tab">
<span>商品评价</span>
</a>
</li>
<li>
<a href="#five" data-toggle="tab">
<span>手机社区</span>
</a>
</li>
</ul>
<div class="clearfix"></div>
<div class="tab-content tab-wraped">
<div id="one" class="tab-pane active">
<ul class="goods-intro-list unstyled" style="list-style: none;">
<li>分辨率:1920*1080(FHD)</li>
<li>后置摄像头:1200万像素</li>
<li>前置摄像头:500万像素</li>
<li>核 数:其他</li>
<li>频 率:以官网信息为准</li>
<li>品牌: Apple</li>
<li>商品名称:APPLEiPhone 6s Plus</li>
<li>商品编号:1861098</li>
<li>商品毛重:0.51kg</li>
<li>商品产地:中国大陆</li>
<li>热点:指纹识别,Apple Pay,金属机身,拍照神器</li>
<li>系统:苹果(IOS)</li>
<li>像素:1000-1600万</li>
<li>机身内存:64GB</li>
</ul>
<!--商品详情-->
<div class="intro-detail">
<div th:utext="${detail.description}"></div>
</div>
</div>
<div id="two" class="tab-pane">
<div class="Ptable">
<div class="Ptable-item" v-for="group in specGroups" :key="group.id">
<h3 v-text="group.name"></h3>
<dl>
<span v-for="param in group.params" :key="param.id">
<dt v-text="param.name"></dt><dd v-text="param.value + (param.unit || '')"></dd>
</span>
</dl>
</div>
</div>
<div class="package-list">
<h3>包装清单</h3>
<p th:text="${detail.packingList}">手机X1、快速指南X1、华为SuperCharge 充电器X1、三包凭证X1、Type-C
数字耳机X1、Type-C 数据线X1、取卡针X1、TPU保护壳X1、USB Type-C转3.5mm耳机转接线X1(备注:最终以实物为准)</p>
</div>
</div>
<div id="three" class="tab-pane">
<p th:text="${detail.afterService}">售后保障</p>
</div>
<div id="four" class="tab-pane">
<p>商品评价</p>
</div>
<div id="five" class="tab-pane">
<p>手机社区</p>
</div>
</div>
</div>
</div>
</div>
<!--like-->
<div class="clearfix"></div>
<div class="like">
<h4 class="kt">猜你喜欢</h4>
<div class="like-list">
<ul class="yui3-g">
<li class="yui3-u-1-6">
<div class="list-wrap">
<div class="p-img">
<img src="/img/_/itemlike01.png"/>
</div>
<div class="attr">
<em>DELL戴尔Ins 15MR-7528SS 15英寸 银色 笔记本</em>
</div>
<div class="price">
<strong>
<em>¥</em>
<i>3699.00</i>
</strong>
</div>
<div class="commit">
<i class="command">已有6人评价</i>
</div>
</div>
</li>
<li class="yui3-u-1-6">
<div class="list-wrap">
<div class="p-img">
<img src="/img/_/itemlike02.png"/>
</div>
<div class="attr">
<em>Apple苹果iPhone 6s/6s Plus 16G 64G 128G</em>
</div>
<div class="price">
<strong>
<em>¥</em>
<i>4388.00</i>
</strong>
</div>
<div class="commit">
<i class="command">已有700人评价</i>
</div>
</div>
</li>
<li class="yui3-u-1-6">
<div class="list-wrap">
<div class="p-img">
<img src="/img/_/itemlike03.png"/>
</div>
<div class="attr">
<em>DELL戴尔Ins 15MR-7528SS 15英寸 银色 笔记本</em>
</div>
<div class="price">
<strong>
<em>¥</em>
<i>4088.00</i>
</strong>
</div>
<div class="commit">
<i class="command">已有700人评价</i>
</div>
</div>
</li>
<li class="yui3-u-1-6">
<div class="list-wrap">
<div class="p-img">
<img src="/img/_/itemlike04.png"/>
</div>
<div class="attr">
<em>DELL戴尔Ins 15MR-7528SS 15英寸 银色 笔记本</em>
</div>
<div class="price">
<strong>
<em>¥</em>
<i>4088.00</i>
</strong>
</div>
<div class="commit">
<i class="command">已有700人评价</i>
</div>
</div>
</li>
<li class="yui3-u-1-6">
<div class="list-wrap">
<div class="p-img">
<img src="/img/_/itemlike05.png"/>
</div>
<div class="attr">
<em>DELL戴尔Ins 15MR-7528SS 15英寸 银色 笔记本</em>
</div>
<div class="price">
<strong>
<em>¥</em>
<i>4088.00</i>
</strong>
</div>
<div class="commit">
<i class="command">已有700人评价</i>
</div>
</div>
</li>
<li class="yui3-u-1-6">
<div class="list-wrap">
<div class="p-img">
<img src="/img/_/itemlike06.png"/>
</div>
<div class="attr">
<em>DELL戴尔Ins 15MR-7528SS 15英寸 银色 笔记本</em>
</div>
<div class="price">
<strong>
<em>¥</em>
<i>4088.00</i>
</strong>
</div>
<div class="commit">
<i class="command">已有700人评价</i>
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<script src="/js/vue/vue.js"></script>
<script src="/js/axios.min.js"></script>
<script src="/js/common.js"></script>
<script th:inline="javascript">
const specialSpec = JSON.parse(/*[[${detail.specialSpec}]]*/ "");
const genericSpec = JSON.parse(/*[[${detail.genericSpec}]]*/ "");
const skus = /*[[${skus}]]*/ [];
const specs = /*[[${specs}]]*/ [];
const params = {
};
specs.forEach(group => {
group.params.forEach(param => {
params[param.id] = param.name;
})
});
// 初始化特有规格参数默认选中一个
const indexes = {
};
const initIndex = skus[0].indexes.split("_");
Object.keys(specialSpec).forEach((id, i) => {
indexes[id] = parseInt(initIndex[i]);
})
const indexArr = skus.map(s => s.indexes);
</script>
<script>
var itemVm = new Vue({
el: "#itemApp",
data: {
ly,
specialSpec,// 特有规格参数模板
params,// 参数对象数组
indexes,// 初始化被选中的参数
num: 1,
},
methods: {
decrement() {
if (this.num > 1) {
this.num--;
}
},
increment() {
this.num++;
},
addCart() {
// 判断是否登录
ly.http.get("/auth/verify").then(() => {
// 已登录
ly.http.post("/cart", {
skuId: this.sku.id,
title: this.sku.title,
image: this.images[0],
price: this.sku.price,
num: this.num,
ownSpec: JSON.stringify(this.ownSpec)
}).then(() => {
// 跳转到购物车列表页
window.location.href = "http://www.leyou.com/cart.html";
}).catch(() => {
alert("添加购物车失败,请重试!");
})
}).catch(() => {
// 获取以前的购物车
const carts = ly.store.get("carts") || [];
// 获取与当前商品id一致的购物车数据
const cart = carts.find(c => c.skuId === this.sku.id);
if (cart) {
// 存在,修改数量
cart.num += this.num;
} else {
// 不存在,新增
carts.push({
skuId: this.sku.id,
title: this.sku.title,
image: this.images[0],
price: this.sku.price,
num: this.num,
ownSpec: JSON.stringify(this.ownSpec)
})
}
// 未登录
ly.store.set("carts", carts);
// 跳转到购物车列表页
window.location.href = "http://www.leyou.com/cart.html";
})
},
locked(id, i) {
// 如果只有一个可选项,永不锁定
if(specialSpec[id].length === 1) return false;
// 如果有其它项未选,不锁定
let boo = true;
Object.keys(this.indexes).forEach(key => {
if (key !== id && this.indexes[key] == null) {
boo = false;
return;
}
});
if (!boo) return false;
// 如果当前项的组合不存在,锁定
const {
...o} = this.indexes;
o[id] = i;
const index = Object.values(o).join("_");
return !indexArr.includes(index);
},
selectSku(id, i) {
// 先判断当前选中的是否是锁定项
const isLocked = this.locked(id, i);
// 无论是否是锁定项,都允许修改
this.indexes[id] = i;
// 如果是锁定项,则需要调整其它项的选中状态
if (isLocked) {
Object.keys(this.indexes).forEach(key => {
if (key !== id) {
const remainSpec = specialSpec[key].filter((e, j) => !this.locked(key, j));
this.indexes[key] = remainSpec.length === 1 ? specialSpec[key].findIndex(e => e === remainSpec[0]) : null;
}
})
}
}
},
computed: {
sku() {
if (Object.values(this.indexes).includes(null)) {
return skus[0];
}
// 获取选中的规格参数的索引
const index = Object.values(this.indexes).join("_");
// 去skus集合寻找与index一致的sku
return skus.find(s => s.indexes === index);
},
images() {
return this.sku.images ? this.sku.images.split(",") : [];
},
specGroups() {
// 获取特有规格参数值
const ownSpec = JSON.parse(this.sku.ownSpec);
specs.forEach(group => {
group.params.forEach(param => {
if (param.generic) {
param.value = genericSpec[param.id];
} else {
param.value = ownSpec[param.id];
}
})
})
return specs;
},
ownSpec() {
const ownSpec = JSON.parse(this.sku.ownSpec);
const obj = {
};
Object.keys(ownSpec).forEach(id => {
obj[this.params[id]] = ownSpec[id];
})
return obj;
}
},
components: {
lyTop: () => import('/js/pages/top.js')
}
});
</script>
<script type="text/javascript" src="/js/plugins/jquery/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#service").hover(function () {
$(".service").show();
}, function () {
$(".service").hide();
});
$("#shopcar").hover(function () {
$("#shopcarlist").show();
}, function () {
$("#shopcarlist").hide();
});
})
</script>
<script type="text/javascript" src="/js/model/cartModel.js"></script>
<script type="text/javascript" src="/js/plugins/jquery.easing/jquery.easing.min.js"></script>
<script type="text/javascript" src="/js/plugins/sui/sui.min.js"></script>
<script type="text/javascript" src="/js/plugins/jquery.jqzoom/jquery.jqzoom.js"></script>
<script type="text/javascript" src="/js/plugins/jquery.jqzoom/zoom.js"></script>
<script type="text/javascript" src="index/index.js"></script>
</body>
</html>
然后我们完成页面跳转:
因为我们的前台代码为已经经过修改后的了因此不需要修改前台代码了。
我们把商品详情页
这个地址指向ly-page,并且让nginx反向代理:
修改nginx:
让nginx拦截item打头的,转到8084,上面的优先级高于下面的。
然后编写跳转conrtoller:
PageController:
package com.leyou.page.web;
import com.leyou.page.service.PageService;
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 java.util.Map;
@Controller
public class PageController {
@Autowired
private PageService pageService;
@GetMapping("item/{id}.html")
public String toItemPage(@PathVariable("id") Long spuId, Model model){
//查询数据模型
Map<String,Object> attributes = pageService.loadModel(spuId);
//准备数据模型
model.addAllAttributes(attributes);
//返回视图
return "item";
}
}
然后我们封装模型数据:
首先我们一起来分析一下,在这个页面中需要哪些数据
我们已知的条件是传递来的spu的id,我们需要根据spu的id查询到下面的数据:
- spu信息
- spu的详情
- spu下的所有sku
- 品牌
- 商品三级分类
- 商品规格参数、规格参数组
以上所需数据中,查询spu的接口目前还没有,我们需要在商品微服务中提供这个接口:
在GoodsService,GoodsController,GoodsApi 中添加代码。
我们在页面展示规格时,需要按组展示:
组内有多个参数,为了方便展示。我们提供一个接口,查询规格组,同时在规格组中持有组内的所有参数。
拓展SpecGroup类:
我们在SpecGroup中添加一个SpecParam的集合,保存改组下所有规格参数
然后提供查询接口:
在SpecificationAPI,SpecificationController,SpecificationService添加代码。
这个代码比较长,在这里给出来
public List<SpecGroup> queryListByCid(Long cid) {
//查询规格组
List<SpecGroup> specGroups = queryGroupByCid(cid);
//查询当前分类下的参数
List<SpecParam> specParams = queryParamList(null,cid, null);
//先把规格参数变成map,map的key是规格组的id,map的值是组下的所有参数
Map<Long,List<SpecParam>> map = new HashMap<>();
for (SpecParam param : specParams) {
if(!map.containsKey(param.getGroupId())){
//这个组id在map中不存在,新增一个List
map.put(param.getGroupId(),new ArrayList<>());
}
map.get(param.getGroupId()).add(param);
}
//填充param到group
for (SpecGroup specGroup : specGroups) {
specGroup.setParams(map.get(specGroup.getId()));
}
return specGroups;
}
在service中,我们调用之前编写过的方法,查询规格组,和规格参数,然后封装返回。
然后我们在ly-page中创建FeignClient
BrandClient:
package com.leyou.page.client;
import com.leyou.item.api.BrandApi;
import org.springframework.cloud.openfeign.FeignClient;
@FeignClient("item-service")
public interface BrandClient extends BrandApi {
}
CategoryClient:
package com.leyou.page.client;
import com.leyou.item.api.CategoryApi;
import org.springframework.cloud.openfeign.FeignClient;
@FeignClient("item-service")
public interface CategoryClient extends CategoryApi {
}
GoodsClient:
package com.leyou.page.client;
import com.leyou.item.api.GoodsApi;
import org.springframework.cloud.openfeign.FeignClient;
@FeignClient("item-service")
public interface GoodsClient extends GoodsApi {
}
SpecificationClient:
package com.leyou.page.client;
import com.leyou.item.api.SpecificationApi;
import org.springframework.cloud.openfeign.FeignClient;
@FeignClient("item-service")
public interface SpecificationClient extends SpecificationApi {
}
然后我们封装数据模型:
我们创建一个PageService,在里面来封装数据模型。
这里要查询的数据:
- SPU
- SpuDetail
- SKU集合
- 商品分类
- 这里值需要分类的id和name就够了,因此我们查询到以后自己需要封装数据
- 品牌
- 规格组
- 查询规格组的时候,把规格组下所有的参数也一并查出,上面提供的接口中已经实现该功能,我们直接调
- sku的特有规格参数
有了规格组,为什么这里还要查询?
因为在SpuDetail中的SpecialSpec中,是以id作为规格参数id作为key,如图:
但是,在页面渲染时,需要知道参数的名称
我们就需要把id和name一一对应起来,因此需要额外查询sku的特有规格参数,然后变成一个id:name的键值对格式。也就是一个Map,方便将来根据id查找!
PageService:
package com.leyou.page.service;
import com.leyou.item.pojo.*;
import com.leyou.page.client.BrandClient;
import com.leyou.page.client.CategoryClient;
import com.leyou.page.client.GoodsClient;
import com.leyou.page.client.SpecificationClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import java.io.File;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
@Slf4j
public class PageService {
@Autowired
private BrandClient brandClient;
@Autowired
private CategoryClient categoryClient;
@Autowired
private GoodsClient goodsClient;
@Autowired
private SpecificationClient specClient;
@Autowired
private TemplateEngine templateEngine;
public Map<String, Object> loadModel(Long spuId) {
Map<String, Object> model = new HashMap<>();
//查询spu
Spu spu = goodsClient.querySpuById(spuId);
//查询skus
List<Sku> skus = spu.getSkus();
//查询详情
SpuDetail detail = spu.getSpuDetail();
//查询brand
Brand brand = brandClient.queryBrandById(spu.getBrandId());
//查询商品分类
List<Category> categories = categoryClient.queryCategoryByIds(
Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
//查询规格参数
List<SpecGroup> specs = specClient.queryGroupByCid(spu.getCid3());
//必须和页面名字保持一致才能找到
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);
return model;
}
public void createHtml(Long spuId){
//上下文,thymeleaf包
Context context = new Context();
context.setVariables(loadModel(spuId));
//输出流
File dest = new File("H:/demo/upload", spuId + ".html");
try(PrintWriter writer = new PrintWriter(dest,"UTF-8")){
//生成HTML
templateEngine.process("item",context,writer);
}catch (Exception e){
log.error("[静态页服务] 生成静态页异常",e);
}
}
}
结果展示:
至此第二部分结束。
3、页面静态化
3.1.简介
3.1.1.问题分析
现在,我们的页面是通过Thymeleaf模板引擎渲染后返回到客户端。在后台需要大量的数据查询,而后渲染得到HTML页面。会对数据库造成压力,并且请求的响应时间过长,并发能力不高。
大家能想到什么办法来解决这个问题?
首先我们能想到的就是缓存技术,比如之前学习过的Redis。不过Redis适合数据规模比较小的情况。假如数据量比较大,例如我们的商品详情页。每个页面如果10kb,100万商品,就是10GB空间,对内存占用比较大。此时就给缓存系统带来极大压力,如果缓存崩溃,接下来倒霉的就是数据库了。
所以缓存并不是万能的,某些场景需要其它技术来解决,比如静态化。
3.1.2.什么是静态化
静态化是指把动态生成的HTML页面变为静态内容保存,以后用户的请求到来,直接访问静态页面,不再经过服务的渲染。
而静态的HTML页面可以部署在nginx中,从而大大提高并发能力,减小tomcat压力。
3.1.3.如何实现静态化
目前,静态化页面都是通过模板引擎来生成,而后保存到nginx服务器来部署。常用的模板引擎比如:
- Freemarker
- Velocity
- Thymeleaf
我们之前就使用的Thymeleaf,来渲染html返回给用户。Thymeleaf除了可以把渲染结果写入Response,也可以写到本地文件,从而实现静态化。
3.2.Thymeleaf实现静态化
3.2.1.概念
先说下Thymeleaf中的几个概念:
- Context:运行上下文
- TemplateResolver:模板解析器
- TemplateEngine:模板引擎
Context
上下文: 用来保存模型数据,当模板引擎渲染时,可以从Context上下文中获取数据用于渲染。
当与SpringBoot结合使用时,我们放入Model的数据就会被处理到Context,作为模板渲染的数据使用。
TemplateResolver
模板解析器:用来读取模板相关的配置,例如:模板存放的位置信息,模板文件名称,模板文件的类型等等。
当与SpringBoot结合时,TemplateResolver已经由其创建完成,并且各种配置也都有默认值,比如模板存放位置,其默认值就是:templates。比如模板文件类型,其默认值就是html。
TemplateEngine
模板引擎:用来解析模板的引擎,需要使用到上下文、模板解析器。分别从两者中获取模板中需要的数据,模板文件。然后利用内置的语法规则解析,从而输出解析后的文件。来看下模板引擎进行处理的函数:
templateEngine.process("模板名", context, writer);
三个参数:
- 模板名称
- 上下文:里面包含模型数据
- writer:输出目的地的流
在输出时,我们可以指定输出的目的地,如果目的地是Response的流,那就是网络响应。如果目的地是本地文件,那就实现静态化了。
而在SpringBoot中已经自动配置了模板引擎,因此我们不需要关心这个。现在我们做静态化,就是把输出的目的地改成本地文件即可!
nginx代理静态页面
接下来,我们修改nginx,让它对商品请求进行监听,指向本地静态页面,如果本地没找到,才进行反向代理
至此,结束第三部分
4、虚拟机安装Rabbitmq
详情见此博客:
虚拟机(Linux)安装Rabbitmq (乐优商城中的相关安装)
至此今天学习结束。