学成在线 第4天 讲义-页面静态化 页面预览

58 篇文章 1 订阅
23 篇文章 5 订阅

1页面静态化需求

1、为什么要进行页面管理?
本项目cms系统的功能就是根据运营需要,对门户等子系统的部分页面进行管理,从而实现快速根据用户需求修改 页面内容并上线的需求。
2、如何修改页面的内容?
在开发中修改页面内容是需要人工编写html及JS文件,CMS系统是通过程序自动化的对页面内容进行修改,通过页面静态化技术生成html页面。
3、如何对页面进行静态化?
一个页面等于模板加数据,在添加页面的时候我们选择了页面的模板。
页面静态化就是将页面模板和数据通过技术手段将二者合二为一,生成一个html网页文件。
4、页面静态化及页面发布流程图如下:
在这里插入图片描述
业务流程如下:
1、获取模型数据
2、制作模板
3、对页面进行静态化
4、将静态化生成的html页面存放文件系统中
5、将存放在文件系统的html文件发布到服务器

2FreeMarker 研究

2.1FreeMarker介绍

1、freemarker是一个用Java开发的模板引擎
在这里插入图片描述
在这里插入图片描述
常用的java模板引擎还有哪些?
Jsp、Freemarker、Thymeleaf 、Velocity 等。

2、模板+数据模型=输出
freemarker并不关心数据的来源,只是根据模板的内容,将数据模型在模板中显示并输出文件(通常为html,也 可以生成其它格式的文本文件)
1、数据模型
数据模型在java中可以是基本类型也可以List、Map、Pojo等复杂类型。
2、来自官方的例子:(https://freemarker.apache.org/docs/dgui_quickstart_basics.html) 数据模型:
在这里插入图片描述
模板:
在这里插入图片描述
输出:
在这里插入图片描述

2.2FreeMarker快速入门

freemarker作为springmvc一种视图格式,默认情况下SpringMVC支持freemarker视图格式。需要创建Spring Boot+Freemarker工程用于测试模板。
2.2.1创建测试工程
创建一个freemarker 的测试工程专门用于freemarker的功能测试与模板的测试。
pom.xml如下

<?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>xc‐framework‐parent</artifactId>
<groupId>com.xuecheng</groupId>
<version>1.0‐SNAPSHOT</version>
<relativePath>../xc‐framework‐parent/pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>test‐freemarker</artifactId>
<dependencies>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring‐boot‐starter‐freemarker</artifactId>
</dependency>
<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
</dependency>
<dependency>
	<groupId>com.squareup.okhttp3</groupId>
	<artifactId>okhttp</artifactId>
</dependency>
<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons‐io</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring‐boot‐starter‐test</artifactId>
</dependency>
</dependencies>
</project>

2.2.2配置文件
配置application.yml和 logback-spring.xml,从cms工程拷贝这两个文件,进行更改, logback-spring.xml无需更改,application.yml内容如下:





server:
port: 8088 #服务端口

spring:
application:
name: test‐freemarker #指定服务名freemarker:
cache: false #关闭模板缓存,方便测试
settings:
template_update_delay: 0  #检查模板更新延迟时间,设置为0表示立即检查,如果时间大于0会有缓存不方便进行模板测试

1.2.3创建模型类
在freemarker的测试工程下创建模型类型用于测试


package com.xuecheng.test.freemarker.model;

import lombok.Data; import lombok.ToString;

import java.util.Date; import java.util.List;

@Data @ToString
public class Student { private String name;//姓名private int age;//年龄
private Date birthday;//生日private Float money;//钱包
private List<Student> friends;//朋友列表private Student bestFriend;//最好的朋友
}

1.2.3创建模板
在 src/main/resources下创建templates,此目录为freemarker的默认模板存放目录。
在templates下创建模板文件test1.ftl,模板中的${name}最终会被freemarker替换成具体的数据。





<!DOCTYPE html>
<html>
<head>
<meta charset="utf‐8">
<title>Hello World!</title>
</head>
<body>
Hello ${name}!
</body>
</html>

1.2.4创建controller
创建Controller类,向Map中添加name,最后返回模板文件。


package com.xuecheng.test.freemarker.controller;

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.client.RestTemplate;

import java.util.Map;

@RequestMapping("/freemarker") @Controller
public class FreemarkerController { @Autowired
RestTemplate restTemplate;

@RequestMapping("/test1")
public String freemarker(Map<String, Object> map){ map.put("name","黑马程序员");
//返回模板文件名称
return "test1";
}
}

1.2.5创建启动类

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

}

1.2.6测试
请 求 :http://localhost:8088/freemarker/test1 屏幕显示:Hello 黑马程序员!

1.3FreeMarker基础

1.3.1核心指令
1.3.1.1数据模型
Freemarker静态化依赖数据模型和模板,下边定义数据模型:
下边方法形参map即为freemarker静态化所需要的数据模型,在map中填充数据:


@RequestMapping("/test1")
public String freemarker(Map<String, Object> map){
//向数据模型放数据map.put("name","黑马程序员"); Student stu1 = new Student(); stu1.setName(" 小 明 "); stu1.setAge(18); stu1.setMondy(1000.86f); stu1.setBirthday(new Date()); Student stu2 = new Student(); stu2.setName(" 小 红 "); stu2.setMondy(200.1f); stu2.setAge(19);
//		stu2.setBirthday(new Date()); List<Student> friends = new ArrayList<>(); friends.add(stu1); stu2.setFriends(friends); stu2.setBestFriend(stu1);
List<Student> stus = new ArrayList<>(); stus.add(stu1);
stus.add(stu2);
//向数据模型放数据map.put("stus",stus);
//准备map数据
HashMap<String,Student> stuMap = new HashMap<>(); stuMap.put("stu1",stu1); stuMap.put("stu2",stu2);
//向数据模型放数据
map.put("stu1",stu1);
//向数据模型放数据map.put("stuMap",stuMap);
//返回模板文件名称
return "test1";
}

1.3.1.2List指令
本节定义freemarker模板,模板中使用freemarker的指令,关于freemarker的指令需要知道:

1、注释,即<#‐‐和‐‐>,介于其之间的内容会被freemarker忽略
2、插值(Interpolation):即${..}部分,freemarker会用真实的值代替${..}
3、FTL指令:和HTML标记类似,名字前加#予以区分,Freemarker会解析标签中的表达式或逻辑。
4、文本,仅文本信息,这些不是freemarker的注释、插值、FTL指令的内容会被freemarker忽略解析,直接输出内   容。

在test1.ftl模板中使用list指令遍历数据模型中的数据:

<table>
<tr>
<td>序号</td>
<td>姓名</td>
<td>年龄</td>
<td>钱包</td>
</tr>
<#list stus as stu>
<tr>
<td>${stu_index + 1}</td>
<td>${stu.name}</td>
<td>${stu.age}</td>
<td>${stu.mondy}</td>
</tr>
</#list>

</table>

3、输出:
Hello 黑马程序员! 序号 姓名 年龄 钱包 1 小明 18 1,000.86 2 小红 19 200.1

说明:
_index:得到循环的下标,使用方法是在stu后边加"_index",它的值是从0开始

1.3.1.3遍历Map数据
1、数据模型
使用map指令遍历数据模型中的stuMap。
2、模板

输出stu1的学生信息:<br/>
姓名:${stuMap['stu1'].name}<br/>
年龄:${stuMap['stu1'].age}<br/>



输出stu1的学生信息:<br/>
姓名:${stuMap.stu1.name}<br/> 年龄:${stuMap.stu1.age}<br/> 遍历输出两个学生信息:<br/>
<table>
<tr>
<td>序号</td>
<td>姓名</td>
<td>年龄</td>
<td>钱包</td>
</tr>
<#list stuMap?keys as k>
<tr>
<td>${k_index + 1}</td>
<td>${stuMap[k].name}</td>
<td>${stuMap[k].age}</td>
<td >${stuMap[k].mondy}</td>
</tr>
</#list>
</table>

输出stu1的学生信息: 姓名:小明
年龄:18
输出stu1的学生信息: 姓名:小明
年龄:18
遍历输出两个学生信息: 序号 姓名 年龄 钱包1 小红 19 200.1
2 小明 18 1,000.86
1.3.1.4if指令
if 指令即判断指令,是常用的FTL指令,freemarker在解析时遇到if会进行判断,条件为真则输出if中间的内容,否则跳过内容不再输出。
1、数据模型:
使用list指令中测试数据模型。
2、模板:

<table>
<tr>
<td>姓名</td>
<td>年龄</td>
<td>钱包</td>

</tr>



<#list stus as stu>
<tr>
<td <#if stu.name =='小明'>style="background:red;"</#if>>${stu.name}</td>
<td>${stu.age}</td>
<td >${stu.mondy}</td>
</tr>
</#list>

</table>

通过阅读上边的代码,实现的功能是:如果姓名为“小明”则背景色显示为红色。

3、输出:

通过测试发现 姓名为小明的背景色为红色。
1.3.2其它指令
1.3.2.1运算符
1、算数运算符 FreeMarker表达式中完全支持算术运算,FreeMarker支持的算术运算符包括:+, - , * , / , % 2、逻辑运算符 逻辑运算符有如下几个: 逻辑与:&& 逻辑或:|| 逻辑非:! 逻辑运算符只能作用于布尔值,否则将产生错误 3、比较运算符 表达式中支持的比较运算符有如下几个: 1 =或者==:判断两个值是否相等. 2 !=:判断两个值是否不等. 3 >
或者gt:判断左边值是否大于右边值 4 >=或者gte:判断左边值是否大于等于右边值 5 <或者lt:判断左边值是否小于右
边值 6 <=或者lte:判断左边值是否小于等于右边值
注意: =和!=可以用于字符串,数值和日期来比较是否相等,但=和!=两边必须是相同类型的值,否则会产生错误,而且FreeMarker是精确比较,“x”,"x ","X"是不等的.其它的运行符可以作用于数字和日期,但不能作用于字符串,大部分的时候,使用gt等字母运算符代替>会有更好的效果,因为 FreeMarker会把>解释成FTL标签的结束字符,当然,也可以使用括号来避免这种情况,如:<#if (x>y)>

1.3.2.2空值处理
1、判断某变量是否存在使用 “??” 用法为:variable??,如果该变量存在,返回true,否则返回false 例:为防止stus为空报错可以加上判断如下:

<#if stus??>
<#list stus as stu>
......
</#list>
</#if>

2、缺失变量默认值使用 “!” 使用!要以指定一个默认值,当变量为空时显示默认值。例: ${name!’’}表示如果name为空显示空字符串。

如果是嵌套对象则建议使用()括起来。

例: ${(stu.bestFriend.name)!’’}表示,如果stu或bestFriend或name为空默认显示空字符串。

1.3.2.3内建函数
内建函数语法格式: 变量+?+函数名称
1、和到某个集合的大小
${集合名?size}
2、日期格式化

显示年月日: ${today?date}
显示时分秒:${today?time}
显示日期+时间:${today?datetime} <br>
自定义格式化: ${today?string("yyyy年MM月")}

3 、 内 建 函 数 c map.put(“point”, 102920122);
point是数字型,使用${point}会显示这个数字的值,不并每三位使用逗号分隔。 如果不想显示为每三位分隔的数字,可以使用c函数将数字型转成字符串输出
${point?c}
4、将json字符串转成对象一个例子:
其中用到了 assign标签,assign的作用是定义一个变量。

<#assign text="{'bank':'工商银行','account':'10101920201920212'}" />
<#assign data=text?eval />
开户行:${data.bank} 账号:${data.account}

1.3.2.4完整的模板
上边测试的模板内容如下,可自行进行对照测试。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf‐8">
<title>Hello World!</title>
</head>
<body>
Hello ${name}!
<br/>
<table>
<tr>
<td>序号</td>
<td>姓名</td>
<td>年龄</td>
<td>钱包</td>
</tr>
<#list stus as stu>
<tr>
<td>${stu_index + 1}</td>
<td <#if stu.name =='小明'>style="background:red;"</#if>>${stu.name}</td>
<td>${stu.age}</td>
<td >${stu.mondy}</td>
</tr>
</#list>

</table>
<br/><br/>
输出stu1的学生信息:<br/>
姓 名 :${stuMap['stu1'].name}<br/> 年龄:${stuMap['stu1'].age}<br/> 输出stu1的学生信息:<br/>
姓名:${stu1.name}<br/> 年龄:${stu1.age}<br/>
遍历输出两个学生信息:<br/>
<table>
<tr>
<td>序号</td>
<td>姓名</td>
<td>年龄</td>
<td>钱包</td>
</tr>
<#list stuMap?keys as k>
<tr>
<td>${k_index + 1}</td>
<td>${stuMap[k].name}</td>
<td>${stuMap[k].age}</td>
<td >${stuMap[k].mondy}</td>
</tr>
</#list>
</table>
</br>
<table>
<tr>
<td>姓名</td>
<td>年龄</td>
<td>出生日期</td>
<td>钱包</td>
<td>最好的朋友</td>
<td>朋友个数</td>
<td>朋友列表</td>
</tr>
<#if stus??>

<#list stus as stu>
<tr>
<td>${stu.name!''}</td>
<td>${stu.age}</td>
<td>${(stu.birthday?date)!''}</td>
<td>${stu.mondy}</td>
<td>${(stu.bestFriend.name)!''}</td>
<td>${(stu.friends?size)!0}</td>
<td>
<#if stu.friends??>
<#list stu.friends as firend>
${firend.name!''}<br/>
</#list>
</#if>
</td>
</tr>
</#list>
</#if>

</table>
<br/>
<#assign text="{'bank':'工商银行','account':'10101920201920212'}" />
<#assign data=text?eval />
开户行:${data.bank} 账号:${data.account}

</body>
</html>

1.3.3静态化测试
在cms中使用freemarker将页面生成html文件,本节测试html文件生成的方法:
1、使用模板文件静态化
定义模板文件,使用freemarker静态化程序生成html文件。
2、使用模板字符串静态化
定义模板字符串,使用freemarker静态化程序生成html文件。

1.3.3.1使用模板文件静态化
在test下创建测试类,并且将main下的resource/templates拷贝到test下,本次测试使用之前我们在main下创建的模板文件。

//基于模板生成静态化文件@Test
public void testGenerateHtml() throws IOException, TemplateException {
//创建配置类
Configuration configuration=new Configuration(Configuration.getVersion());
//设置模板路径
String classpath = this.getClass().getResource("/").getPath(); configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
//设置字符集
configuration.setDefaultEncoding("utf‐8");
//加载模板
Template template = configuration.getTemplate("test1.ftl");
//数据模型
Map<String,Object> map = new HashMap<>(); map.put("name","黑马程序员");
//静态化
String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
//静态化内容System.out.println(content);
InputStream inputStream = IOUtils.toInputStream(content);
//输出文件
FileOutputStream fileOutputStream = new FileOutputStream(new File("d:/test1.html"));
int copy = IOUtils.copy(inputStream, fileOutputStream);
}



1.3.3.2使用模板字符串静态化

//基于模板字符串生成静态化文件
@Test
public void testGenerateHtmlByString() throws IOException, TemplateException {
//创建配置类
Configuration configuration=new Configuration(Configuration.getVersion());
//模板内容,这里测试时使用简单的字符串作为模板String templateString="" +
"<html>\n" +
"<head></head>\n" + "	<body>\n" +
"名称:${name}\n" +
"	</body>\n" +
"</html>";
//模板加载器
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader(); stringTemplateLoader.putTemplate("template",templateString); configuration.setTemplateLoader(stringTemplateLoader);
//得到模板
Template template = configuration.getTemplate("template","utf‐8");

//数据模型
Map<String,Object> map = new HashMap<>(); map.put("name","黑马程序员");
//静态化
String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
//静态化内容System.out.println(content);
InputStream inputStream = IOUtils.toInputStream(content);
//输出文件
FileOutputStream fileOutputStream = new FileOutputStream(new File("d:/test1.html"));
IOUtils.copy(inputStream, fileOutputStream);
}

3页面静态化

3.1页面静态化流程

通过上边对FreeMarker的研究我们得出:模板+数据模型=输出,页面静态化需要准备数据模型和模板,先知道数据模型的结构才可以编写模板,因为在模板中要引用数据模型中的数据,本节将系统讲解CMS页面数据模型获取、 模板管理及静态化的过程。
下边讨论一个问题:如何获取页面的数据模型?
CMS管理了各种页面,CMS对页面进行静态化时需要数据模型,但是CMS并不知道每个页面的数据模型的具体内容,它只管执行静态化程序便可对页面进行静态化,所以CMS静态化程序需要通过一种通用的方法来获取数据模 型。
在编辑页面信息时指定一个DataUrl,此DataUrl便是获取数据模型的Url,它基于Http方式,CMS对页面进行静态 化时会从页面信息中读取DataUrl,通过Http远程调用的方法请求DataUrl获取数据模型。
管理员怎么知道DataUrl的内容呢? 举例说明:
此页面是轮播图页面,它的DataUrl由开发轮播图管理的程序员提供。
此页面是精品课程推荐页面,它的DataUrl由精品课程推荐的程序员提供。此页面是课程详情页面,它的DataUrl由课程管理的程序员提供。
页面静态化流程如下图:
1、静态化程序首先读取页面获取DataUrl。
2、静态化程序远程请求DataUrl得到数据模型。
3、获取页面模板。
4、执行页面静态化。
在这里插入图片描述

3.2数据模型

3.2.1轮播图DataUrl接口
3.2.1.1需求分析
CMS中有轮播图管理、精品课程推荐的功能,以轮播图管理为例说明:轮播图管理是通过可视化的操作界面由管理 员指定轮播图图片地址,最后将轮播图图片地址保存在cms_config集合中,下边是轮播图数据模型:
在这里插入图片描述
针对首页的轮播图信息、精品推荐等信息的获取统一提供一个Url供静态化程序调用,这样我们就知道了轮播图页 面、精品课程推荐页面的DataUrl,管理在页面配置中将此Url配置在页面信息中。
本小节开发一个查询轮播图、精品推荐信息的接口,此接口供静态化程序调用获取数据模型。
3.2.1.2接口定义
轮播图信息、精品推荐等信息存储在MongoDB的cms_config集合中。
在这里插入图片描述
cms_config有固定的数据结构,如下:

@Data @ToString
@Document(collection = "cms_config") public class CmsConfig {

@Id
private String id;//主键
private String name;//数据模型的名称
private List<CmsConfigModel> model;//数据模型项目

}

数据模型项目内容如下:

@Data @ToString
public class CmsConfigModel { 
private String key;//主键
private String name;//项目名称
private String url;//项目url
private Map mapValue;//项目复杂值
private String value;//项目简单值

}

上边的模型结构可以对照cms_config中的数据进行分析。其中,在mapValue 中可以存储一些复杂的数据模型内容。

根据配置信息Id查询配置信息,定义接口如下:







@Api(value="cms配置管理接口",description = "cms配置管理接口,提供数据模型的管理、查询接口") public interface CmsConfigControllerApi {

@ApiOperation("根据id查询CMS配置信息") public CmsConfig getmodel(String id);

}

3.2.1.3Dao
定义CmsConfig的dao接口:


public interface CmsConfigRepository extends MongoRepository<CmsConfig,String> {
}

3.2.1.4Service
定义CmsConfigService实现根据id查询CmsConfig信息。

@Service
public class CmsConfigService { 
@Autowired
CmsConfigRepository cmsConfigRepository;
//根据id查询配置管理信息
public CmsConfig getConfigById(String id){
Optional<CmsConfig> optional = cmsConfigRepository.findById(id); if(optional.isPresent()){
CmsConfig cmsConfig = optional.get(); return cmsConfig;
}
return null;
}
}

3.2.1.5Controller

@RestController @RequestMapping("/cms/config")
public class CmsConfigController implements CmsConfigControllerApi { @Autowired
CmsConfigService cmsConfigService;

@Override @GetMapping("/getmodel/{id}")
public CmsConfig getmodel(@PathVariable("id") String id) { return cmsConfigService.getConfigById(id);
}
}

3.2.1.6测试
使用postman测试接口:
get请求:http://localhost:31001/cms/config/getmodel/5a791725dd573c3574ee333f (轮播图信息)

3.2.3 远程请求接口
SpringMVC提供 RestTemplate请求http接口,RestTemplate的底层可以使用第三方的http客户端工具实现http 的请求,常用的http客户端工具有Apache HttpClient、OkHttpClient等,本项目使用OkHttpClient完成http请求, 原因也是因为它的性能比较出众。
1、添加依赖

<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>

2、配置RestTemplate
在SpringBoot启动类中配置 RestTemplate

...
public class ManageCmsApplication {
public static void main(String[] args) { SpringApplication.run(ManageCmsApplication.class,args);
}

@Bean
public RestTemplate restTemplate() {
return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
}
}

3、测试RestTemplate
根据url获取数据,并转为map格式。

@Test
public void testRestTemplate(){ ResponseEntity<Map> forEntity =
restTemplate.getForEntity("http://localhost:31001/cms/config/get/5a791725dd573c3574ee333f", Map.class);
System.out.println(forEntity);
}

3.3模板管理

3.3.1模板管理业务流程
CMS提供模板管理功能,业务流程如下:
在这里插入图片描述
1、要增加新模板首先需要制作模板,模板的内容就是Freemarker ftl模板内容。
2、通过模板管理模块功能新增模板、修改模板、删除模板。
3、模板信息存储在MongoDB数据库,其中模板信息存储在cms_template集合中,模板文件存储在GridFS文件系 统中。
cms_template集合:
下边是一个模板的例子:

{
"_id" : ObjectId("5a962b52b00ffc514038faf7"),
"_class" : "com.xuecheng.framework.domain.cms.CmsTemplate", "siteId" : "5a751fab6abb5044e0d19ea1",
"templateName" : "首页",
"templateParameter" : "",
"templateFileId" : "5a962b52b00ffc514038faf5"
}

上边模板信息中templateFileId是模板文件的ID,此ID对应GridFS文件系统中文件ID。

3.3.2模板制作
3.3.2.1编写模板文件
1、轮播图页面原型
在门户的静态工程目录有轮播图的静态页面,路径是:/include/index_banner.html。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF‐8">
<title>Title</title>
<link rel="stylesheet" href="http://www.xuecheng.com/plugins/normalize‐css/normalize.css" />
<link rel="stylesheet" href="http://www.xuecheng.com/plugins/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="http://www.xuecheng.com/css/page‐learing‐index.css" />
<link rel="stylesheet" href="http://www.xuecheng.com/css/page‐header.css" />
</head>
<body>
<div class="banner‐roll">
<div class="banner‐item">
<div class="item" style="background‐image: url(../img/widget‐bannerB.jpg);"></div>
<div class="item" style="background‐image: url(../img/widget‐bannerA.jpg);"></div>
<div class="item" style="background‐image: url(../img/widget‐banner3.png);"></div>
<div class="item" style="background‐image: url(../img/widget‐bannerB.jpg);"></div>
<div class="item" style="background‐image: url(../img/widget‐bannerA.jpg);"></div>
<div class="item" style="background‐image: url(../img/widget‐banner3.png);"></div>
</div>
<div class="indicators"></div>
</div>
<script type="text/javascript" src="http://www.xuecheng.com/plugins/jquery/dist/jquery.js">
</script>
<script type="text/javascript" src="http://www.xuecheng.com/plugins/bootstrap/dist/js/bootstrap.js"></script>
<script type="text/javascript">
var tg = $('.banner‐item .item'); var num = 0;
for (i = 0; i < tg.length; i++) {
$('.indicators').append('<span></span>');
$('.indicators').find('span').eq(num).addClass('active');
}

function roll() { tg.eq(num).animate({
'opacity': '1', 'z‐index': num
}, 1000).siblings().animate({ 'opacity': '0',
'z‐index': 0
}, 1000);

$('.indicators').find('span').eq(num).addClass('active').siblings().removeClass('active');  if (num >= tg.length ‐ 1) {
num = 0;
} else {
num++;
}
}
$('.indicators').find('span').click(function() { num = $(this).index();

roll();
});
var timer = setInterval(roll, 3000);
$('.banner‐item').mouseover(function() { clearInterval(timer)
});
$('.banner‐item').mouseout(function() { timer = setInterval(roll, 3000)
});
</script>
</body>
</html>

2、数据模型为:
通过http 获取到数据模型如下:
下图数据模型的图片路径改成可以浏览的正确路径。

{
"id": "5a791725dd573c3574ee333f",
"name": "轮播图", "model": [
{
"key": "banner1",
"name": "轮播图1地址", "url": null, "mapValue": null,
"value": "http://www.xuecheng.com/img/widget‐bannerB.jpg"
},
{
"key": "banner2",
"name": "轮播图2地址", "url": null, "mapValue": null,
"value": "http://www.xuecheng.com/img/widget‐bannerA.jpg"
},
{
"key": "banner3",
"name": "轮播图3地址", "url": null, "mapValue": null,
"value": "http://www.xuecheng.com/img/widget‐banner3.jpg"
}
]
}

3、编写模板
在freemarker测试工程中新建模板index_banner.ftl。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF‐8">
<title>Title</title>
<link rel="stylesheet" href="http://www.xuecheng.com/plugins/normalize‐css/normalize.css" />
<link rel="stylesheet" href="http://www.xuecheng.com/plugins/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="http://www.xuecheng.com/css/page‐learing‐index.css" />
<link rel="stylesheet" href="http://www.xuecheng.com/css/page‐header.css" />
</head>
<body>
<div class="banner‐roll">
<div class="banner‐item">
<#if model??>
<#list model as item>
<div class="item" style="background‐image: url(${item.value});"></div>
</#list>
</#if>
<#‐‐ <div class="item" style="background‐image: url(../img/widget‐bannerA.jpg);"></div>
<div class="item" style="background‐image: url(../img/widget‐banner3.png);"></div>
<div class="item" style="background‐image: url(../img/widget‐bannerB.jpg);"></div>
<div class="item" style="background‐image: url(../img/widget‐bannerA.jpg);"></div>
<div class="item" style="background‐image: url(../img/widget‐banner3.png);"></div>‐‐>
</div>
<div class="indicators"></div>
</div>
<script type="text/javascript" src="http://www.xuecheng.com/plugins/jquery/dist/jquery.js">
</script>
<script type="text/javascript" src="http://www.xuecheng.com/plugins/bootstrap/dist/js/bootstrap.js"></script>
<script type="text/javascript">
var tg = $('.banner‐item .item'); var num = 0;
for (i = 0; i < tg.length; i++) {
$('.indicators').append('<span></span>');
$('.indicators').find('span').eq(num).addClass('active');
}

function roll() { tg.eq(num).animate({
'opacity': '1', 'z‐index': num
}, 1000).siblings().animate({ 'opacity': '0',
'z‐index': 0
}, 1000);

$('.indicators').find('span').eq(num).addClass('active').siblings().removeClass('active');  if (num >= tg.length ‐ 1) {
num = 0;
} else {

num++;
}
}
$('.indicators').find('span').click(function() { num = $(this).index();
roll();
});
var timer = setInterval(roll, 3000);
$('.banner‐item').mouseover(function() { clearInterval(timer)
});
$('.banner‐item').mouseout(function() { timer = setInterval(roll, 3000)
});
</script>
</body>
</html>

3.3.2.2模板测试
在freemarker测试工程编写一个方法测试轮播图模板,代码如下:


@Autowired
RestTemplate restTemplate;

@RequestMapping("/banner")
public String index_banner(Map<String, Object> map){
String dataUrl = "http://localhost:31001/cms/config/getmodel/5a791725dd573c3574ee333f"; ResponseEntity<Map> forEntity = restTemplate.getForEntity(dataUrl, Map.class);
Map body = forEntity.getBody(); map.putAll(body);
return "index_banner";
}

请求:http://localhost:8088/freemarker/banner
在这里插入图片描述
3.3.3GridFS研究
3.3.3.1GridFS介绍
GridFS是MongoDB提供的用于持久化存储文件的模块,CMS使用MongoDB存储数据,使用GridFS可以快速集成 开发。
它的工作原理是:
在GridFS存储文件是将文件分块存储,文件会按照256KB的大小分割成多个块进行存储,GridFS使用两个集合
(collection)存储文件,一个集合是chunks, 用于存储文件的二进制数据;一个集合是files,用于存储文件的元数据信息(文件名称、块大小、上传时间等信息)。
从GridFS中读取文件要对文件的各各块进行组装、合并。
详细参考:https://docs.mongodb.com/manual/core/gridfs/
3.3.3.2GridFS存取文件测试
1、存文件
使用GridFsTemplate存储文件测试代码: 向测试程序注入GridFsTemplate。


@Test
public void testGridFs() throws FileNotFoundException {
//要存储的文件
File file = new File("d:/index_banner.html");
//定义输入流
FileInputStream inputStram = new FileInputStream(file);
//向GridFS存储文件
ObjectId objectId = = gridFsTemplate.store(inputStram, "轮播图测试文件01", "");
//得到文件ID
String fileId = objectId.toString(); System.out.println(file);
}

存储原理说明:
文件存储成功得到一个文件id
此文件id是fs.files集合中的主键。
可以通过文件id查询fs.chunks表中的记录,得到文件的内容
2、读取文件
1)在config包中定义Mongodb的配置类,如下: GridFSBucket用于打开下载流对象

@Configuration
public class MongoConfig {

@Value("${spring.data.mongodb.database}") String db;

@Bean
public GridFSBucket getGridFSBucket(MongoClient mongoClient){ MongoDatabase database = mongoClient.getDatabase(db); GridFSBucket bucket = GridFSBuckets.create(database); return bucket;
}
}

2)测试代码如下


@SpringBootTest @RunWith(SpringRunner.class) public class GridFsTest {

@Autowired
GridFsTemplate gridFsTemplate;

@Autowired
GridFSBucket gridFSBucket;

@Test
public void queryFile() throws IOException { String fileId = "5b9c54e264c614237c271a99";
//根据id查询文件
GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId)));
//打开下载流对象
GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
//创建gridFsResource,用于获取流对象
GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream);
//获取流中的数据
String s = IOUtils.toString(gridFsResource.getInputStream(), "UTF‐8"); System.out.println(s);
}
...

3、删除文件





//删除文件@Test
public void testDelFile() throws IOException {
//根据文件id删除fs.files和fs.chunks中的记录gridFsTemplate.delete(Query.query(Criteria.where("_id").is("5b32480ed3a022164c4d2f92")));
}

3.3.4模板存储
根据模板管理的流程,最终将模板信息存储到MongoDB的cms_template中,将模板文件存储到GridFS中。 模板管理功能在课堂中不再讲解,教学中手动向cms_template及GridFS中存储模板,方法如下:
1、添加模板
1)使用GridFS测试代码存储模板文件到GridFS,并得到文件id. 2)向cms_template添加记录。
在这里插入图片描述
2、删除模板
1)使用GridFS测试代码根据文件id删除模板文件。2)根据模板id删除cms_template中的记录。

3、修改模板信息
使用Studio 3T修改cms_template中的记录。

4、修改模板文件
1)通过Studio 3T修改模板文件(此方法限文件小于256K)
可以通过Studio 3T修改模板文件,先找到模板文件,再导入进去:
在这里插入图片描述

3.4静态化测试

上边章节完成了数据模型和模板管理的测试,下边测试整个页面静态化的流程,流程如下:
1、填写页面DataUrl
在编辑cms页面信息界面填写DataUrl,将此字段保存到cms_page集合中。
2、静态化程序获取页面的DataUrl
3、静态化程序远程请求DataUrl获取数据模型。
4、静态化程序获取页面的模板信息
5、执行页面静态化
3.4.1填写页面DataUrl
修改页面管理模板代码,实现编辑页面DataUrl。
注意:此地址由程序员提供给系统管理员,由系统管理员录入到系统中。下边实现页面修改界面录入DataUrl:
1、修改页面管理前端的page_edit.vue
在表单中添加dataUrl输入框:

<el‐form‐item label="数据Url" prop="dataUrl">
<el‐input v‐model="pageForm.dataUrl" auto‐complete="off" ></el‐input>
</el‐form‐item>

2、修改页面管理服务端PageService
在更新cmsPage数据代码中添加:

// 更 新 dataUrl one.setDataUrl(cmsPage.getDataUrl());

3.4.2静态化程序
在PageService中定义页面静态化方法,如下:

//页面静态化
public String getPageHtml(String pageId){
//获取页面模型数据
Map model = this.getModelByPageId(pageId); if(model == null){
//获取页面模型数据为空
ExceptionCast.cast(CmsCode.CMS_GENERATEHTML_DATAISNULL);
}
//获取页面模板
String templateContent = getTemplateByPageId(pageId); if(StringUtils.isEmpty(templateContent)){
//页面模板为空
ExceptionCast.cast(CmsCode.CMS_GENERATEHTML_TEMPLATEISNULL);
}
//执行静态化
String html = generateHtml(templateContent, model); if(StringUtils.isEmpty(html)){
ExceptionCast.cast(CmsCode.CMS_GENERATEHTML_HTMLISNULL);
}
return html;

}
//页面静态化
public String generateHtml(String template,Map model){ try {
//生成配置类
Configuration configuration = new Configuration(Configuration.getVersion());
//模板加载器
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader(); stringTemplateLoader.putTemplate("template",template);
//配置模板加载器
configuration.setTemplateLoader(stringTemplateLoader);
//获取模板
Template template1 = configuration.getTemplate("template");
String html = FreeMarkerTemplateUtils.processTemplateIntoString(template1, model); return html;
} catch (Exception e) { e.printStackTrace();
}
return null;

}
//获取页面模板
public String getTemplateByPageId(String pageId){
//查询页面信息
CmsPage cmsPage = this.getById(pageId); if(cmsPage == null){
//页面不存在
ExceptionCast.cast(CmsCode.CMS_PAGE_NOTEXISTS);
}
//页面模板
String templateId = cmsPage.getTemplateId(); if(StringUtils.isEmpty(templateId)){
//页面模板为空
ExceptionCast.cast(CmsCode.CMS_GENERATEHTML_TEMPLATEISNULL);
}
Optional<CmsTemplate> optional = cmsTemplateRepository.findById(templateId); if(optional.isPresent()){
CmsTemplate cmsTemplate = optional.get();
//模板文件id
String templateFileId = cmsTemplate.getTemplateFileId();
//取出模板文件内容GridFSFile gridFSFile =
gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(templateFileId)));
//打开下载流对象
GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
//创建GridFsResource
GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream); try {
String content = IOUtils.toString(gridFsResource.getInputStream(), "utf‐8"); return content;
} catch (IOException e) { e.printStackTrace();
}

}
return null;
}
//获取页面模型数据
public Map getModelByPageId(String pageId){
//查询页面信息
CmsPage cmsPage = this.getById(pageId); if(cmsPage == null){
//页面不存在

ExceptionCast.cast(CmsCode.CMS_PAGE_NOTEXISTS);
}
//取出dataUrl
String dataUrl = cmsPage.getDataUrl(); if(StringUtils.isEmpty(dataUrl)){
ExceptionCast.cast(CmsCode.CMS_GENERATEHTML_DATAURLISNULL);
}
ResponseEntity<Map> forEntity = restTemplate.getForEntity(dataUrl, Map.class); Map body = forEntity.getBody();
return body;
}

单元测试getPageHtml方法,过程略。

4页面预览

4.1页面预览开发

4.1.1需求分析
页面在发布前增加页面预览的步骤,方便用户检查页面内容是否正确。页面预览的流程如下:
在这里插入图片描述
1、用户进入cms前端,点击“页面预览”在浏览器请求cms页面预览链接。 2、cms根据页面id查询DataUrl并远程请求DataUrl获取数据模型。
3、cms根据页面id查询页面模板内容
4、cms执行页面静态化。
5、cms将静态化内容响应给浏览器。
6、在浏览器展示页面内容,实现页面预览的功能。
4.1.2搭建环境
在cms服务需要集成freemarker:
1、在CMS服务中加入freemarker的依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring‐boot‐starter‐freemarker</artifactId>
</dependency>

2、在application.yml配置freemarker


spring:
freemarker:
cache: false #关闭模板缓存,方便测试settings:
template_update_delay: 0

4.1.3Service
静态化方法在静态化测试章节已经实现。

4.1.4Controller
调用service的静态化方法,将静态化内容通过response输出到浏览器显示 创建CmsPagePreviewController类,用于页面预览:
请求页面id,查询得到页面的模板信息、数据模型url,根据模板和数据生成静态化内容,并输出到浏览器。


@Controller
public class CmsPagePreviewController extends BaseController { @Autowired
PageService pageService;

//接收到页面id
@RequestMapping(value="/cms/preview/{pageId}",method = RequestMethod.GET)
public void preview(@PathVariable("pageId")String pageId){
String pageHtml = pageService.getPageHtml(pageId); if(StringUtils.isNotEmpty(pageHtml)){
try {
ServletOutputStream outputStream = response.getOutputStream(); outputStream.write(pageHtml.getBytes("utf‐8"));
} catch (IOException e) { e.printStackTrace();
}

}
}

4.2页面预览测试

4.2.1配置Nginx代理
为了通过nginx请求静态资源(css、图片等),通过nginx代理进行页面预览。 在www.xuecheng.com虚拟主机配置:

#页面预览
location /cms/preview/ {
proxy_pass http://cms_server_pool/cms/preview/;
}

配置cms_server_pool将请求转发到cms:

#cms页面预览
upstream cms_server_pool{
server 127.0.0.1:31001 weight=10;
}

重新加载nginx 配置文件。
从cms_page找一个页面进行测试。注意:页面配置一定要正确,需设置正确的模板id和dataUrl。 在 浏 览 器 打 开 :http://www.xuecheng.com/cms/preview/5a795ac7dd573c04508f3a56 5a795ac7dd573c04508f3a56:轮播图页面的id
4.2.2添加“页面预览”链接
在页面列表添加“页面预览”链接,修改page_list.vue:


<template slot‐scope="page">
<el‐button @click="edit(page.row.pageId)" type="text" size="small">修改</el‐button>
<el‐button @click="del(page.row.pageId)" type="text" size="small">删除</el‐button>
<el‐button @click="preview(page.row.pageId)" type="text" size="small">页面预览</el‐button>
...

添加preview方法:

//页面预览preview(pageId){
window.open("http://www.xuecheng.com/cms/preview/"+pageId)
},

效果:
在这里插入图片描述
点击轮播图页面的“页面预览”,预览页面效果。
在这里插入图片描述

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值