一、页面静态化需求
1.1 为什么要进行页面管理
本项目cms系统的功能就是根据运营需要,对门户等子系统的部分页面进行管理,从而实现快速根据用户需求修改页面内容并上线的需求。
1.2 如何修改页面的内容
在开发中修改页面内容是需要人工编写html及JS文件,CMS系统是通过程序自动化的对页面内容进行修改,通过页面静态化技术生成html页面。
1.3 如何对页面进行静态化
一个页面等于模板加数据,在添加页面的时候我们选择了页面的模板。
页面静态化就是将页面模板和数据通过技术手段将二者合二为一,生成一个html网页文件
1.4 页面静态化及页面发布流程如下图

业务流程如下:
- 获取模板数据
- 制作模板
- 对页面进行静态化
- 将静态化生成的html页面存放在文件系统中
- 将存在在文件系统的html文件发布到服务器上
二、FreeMaker入门
三、页面静态化
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有固定的数据结构,如下:
package com.xuecheng.framework.domain.cms;
import lombok.Data;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.List;
/**
* @author 98050
*/
@Data
@ToString
@Document(collection = "cms_config")
public class CmsConfig {
@Id
private String id;
private String name;
private List<CmsConfigModel> model;
}
数据模型内容如下:
package com.xuecheng.framework.domain.cms;
import lombok.Data;
import lombok.ToString;
import java.util.Map;
/**
* @author 98050
*/
@Data
@ToString
public class CmsConfigModel {
/**
* 主键
*/
private String key;
/**
* 项目名称
*/
private String name;
/**
* 项目url
*/
private String url;
/**
* 项目复杂值
*/
private Map mapValue;
/**
* 项目简单值
*/
private String value;
}
上边的模型结构可以对照cms_config中的数据进行分析。
其中,在mapValue 中可以存储一些复杂的数据模型内容。
根据配置信息Id查询配置信息,定义接口如下:
package com.xuecheng.api.cms;
import com.xuecheng.framework.domain.cms.CmsConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @Author: 98050
* @Time: 2019-03-28 16:44
* @Feature: cms配置管理接口
*/
@RequestMapping("/cms/config")
@Api(value = "cms配置信息管理接口",description = "cms配置信息管理接口,提供对配置信息的CRUD")
public interface CmsConfigControllerApi {
/**
* 根据id查询CMS配置信息
* @param id
* @return
*/
@ApiOperation("根据id查询CMS配置信息")
@GetMapping("/getModel/{id}")
CmsConfig getModel(@PathVariable("id") String id);
}
3.2.1.3 DAO
package com.xuecheng.managecms.dao;
import com.xuecheng.framework.domain.cms.CmsConfig;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
* @Author: 98050
* @Time: 2019-03-28 16:46
* @Feature:
*/
public interface CmsConfigRepository extends MongoRepository<CmsConfig,String> {
}
3.2.1.4 Service
接口:
package com.xuecheng.managecms.service;
import com.xuecheng.framework.domain.cms.CmsConfig;
/**
* @Author: 98050
* @Time: 2019-03-28 16:48
* @Feature:
*/
public interface CmsConfigService {
/**
* 根据id查询配置管理信息
* @param id
* @return
*/
CmsConfig getConfigById(String id);
}
实现:
package com.xuecheng.managecms.service.impl;
import com.xuecheng.framework.domain.cms.CmsConfig;
import com.xuecheng.managecms.dao.CmsConfigRepository;
import com.xuecheng.managecms.service.CmsConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
/**
* @Author: 98050
* @Time: 2019-03-28 16:49
* @Feature:
*/
@Service
public class CmsConfigServiceImpl implements CmsConfigService {
@Autowired
private CmsConfigRepository cmsConfigRepository;
/**
* 根据id查询配置管理信息
* @param id
* @return
*/
@Override
public CmsConfig getConfigById(String id) {
Optional<CmsConfig> optional = cmsConfigRepository.findById(id);
return optional.orElse(null);
}
}
3.2.1.5 Controller
package com.xuecheng.managecms.controller;
import com.xuecheng.api.cms.CmsConfigControllerApi;
import com.xuecheng.framework.domain.cms.CmsConfig;
import com.xuecheng.managecms.service.CmsConfigService;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
/**
* @Author: 98050
* @Time: 2019-03-28 16:52
* @Feature:
*/
@RestController
@RequestMapping("/cms/config")
public class CmsConfigController implements CmsConfigControllerApi {
@Autowired
private CmsConfigService cmsConfigService;
@Override
@GetMapping("/getModel/{id}")
public CmsConfig getModel(@PathVariable("id") String id) {
return cmsConfigService.getConfigById(id);
}
}
3.2.1.6 测试
接口文档测试:

结果:

3.2.2 远程请求接口
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
@Bean
public RestTemplate restTemplate(){
return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
}
3、测试RestTemplate
根据url获取数据,并且转为map格式。
package com.xuecheng.managecms;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
/**
* @Author: 98050
* @Time: 2019-03-28 17:28
* @Feature:
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class CmsPageConfigTest {
@Autowired
private RestTemplate restTemplate;
@Test
public void testRestTemplate(){
ResponseEntity<Map> entity = this.restTemplate.getForEntity("http://localhost:31001/cms/config/getModel/5a791725dd573c3574ee333f", Map.class);
System.out.println(entity.getBody());
}
}
结果:

3.3 模板管理
3.3.1 模板管理业务流程
CMS提供模板管理功能,业务流程如下:

1、要增加新模板首先需要制作模板,模板的内容就是Freemarker ftl模板内容。
2、通过模板管理模块功能新增模板、修改模板、删除模板。
3、模板信息存储在MongoDB数据库,其中模板信息存储在cms_template集合中,模板文件存储在GridFS文件系统中。
cms_template集合:

上边模板信息中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="/plugins/normalize-css/normalize.css" />
<link rel="stylesheet" href="/plugins/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="/css/page-learing-index.css" />
<link rel="stylesheet" href="/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="/plugins/jquery/dist/jquery.js"></script>
<script type="text/javascript" src="/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://192.168.101.64/group1/M00/00/01/wKhlQFp5wnCAG-kAAATMXxpSaMg864.png"
},
{
"key": "banner2",
"name": "轮播图2地址",
"url": null,
"mapValue": null,
"value": "http://192.168.101.64/group1/M00/00/01/wKhlQVp5wqyALcrGAAGUeHA3nvU867.jpg"
},
{
"key": "banner3",
"name": "轮播图3地址",
"url": null,
"mapValue": null,
"value": "http://192.168.101.64/group1/M00/00/01/wKhlQFp5wtWAWNY2AAIkOHlpWcs395.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">
<#--<div class="item" style="background-image: url(http://www.xuecheng.com/img/widget-bannerB.jpg);"></div>
<div class="item" style="background-image: url(http://www.xuecheng.com/img/widget-bannerA.jpg);"></div>
<div class="item" style="background-image: url(http://www.xuecheng.com/img/widget-banner3.png);"></div>
<div class="item" style="background-image: url(http://www.xuecheng.com/img/widget-bannerB.jpg);"></div>
<div class="item" style="background-image: url(http://www.xuecheng.com/img/widget-bannerA.jpg);"></div>
<div class="item" style="background-image: url(http://www.xuecheng.com/img/widget-banner3.png);"></div>-->
<#if model??>
<#list model as item>
<div class="item" style="background-image: url(${item.value});"></div>
</#list>
</#if>
</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> entity = restTemplate.getForEntity(dataUrl, Map.class);
Map body = entity.getBody();
System.out.println(body);
if (body != null) {
map.putAll(body);
}
return "index_banner";
}
问题:图片服务器没有搭建,修改一下模型数据
{
"_id" : ObjectId("5a791725dd573c3574ee333f"),
"_class" : "com.xuecheng.framework.domain.cms.CmsConfig",
"name" : "轮播图",
"model" : [
{
"key" : "banner1",
"name" : "轮播图1地址",
"value" : "http://mycsdnblog.work/201919291432-F.png"
},
{
"key" : "banner2",
"name" : "轮播图2地址",
"value" : "http://mycsdnblog.work/201919291433-e.png"
},
{
"key" : "banner3",
"name" : "轮播图3地址",
"value" : "http://mycsdnblog.work/201919291433-0.png"
}
]
}
请求:http://localhost:8088/freemarker/banner
结果:

3.3.3 GridFS研究
3.3.3.1 GridFS介绍
GridFS是MongoDB提供的用于持久化存储文件的模块,CMS使用MongoDB存储数据,使用GridFS可以快速集成开发。
它的工作原理是:在GridFS存储文件是将文件分块存储,文件会按照256KB的大小分割成多个块进行存储,GridFS使用两个集合(collection)存储文件,一个集合是chunks, 用于存储文件的二进制数据;一个集合是files,用于存储文件的元数据信息(文件名称、块大小、上传时间等信息)。
从GridFS中读取文件要对文件的各各块进行组装、合并。
3.3.3.2 GridFS存取文件测试
存文件
使用GridFsTemplate存储文件测试代码:
package com.xuecheng.managecms;
import org.bson.types.ObjectId;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
/**
* @Author: 98050
* @Time: 2019-03-29 15:57
* @Feature:
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class GridFsTest {
@Autowired
private GridFsTemplate gridFsTemplate;
@Test
public void testGridFs() throws FileNotFoundException {
//1.要存储的文件
File file = new File("D:\\test1.html");
//2.定义输入流
FileInputStream inputStream = new FileInputStream(file);
//3.向GridFS存储文件
ObjectId objectId = gridFsTemplate.store(inputStream, "测试文件", "");
//4.得到文件ID
String fileId = objectId.toString();
System.out.println(fileId);
}
}
存储原理:
文件存储成功得到一个文件Id
此文件Id是fs.files集合中的主键
可以通过文件id查询fs.chunks表中的记录,得到文件的内容。
读取文件
1)在config包中定义Mongodb的配置类,如下:
GridFSBucket用于打开下载流对象
package com.xuecheng.managecms.config;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Author: 98050
* @Time: 2019-03-29 16:12
* @Feature: mongodb配置类
*/
@Configuration
public class MongoConfig {
@Value("${spring.data.mongodb.database}")
private String db;
@Bean
public GridFSBucket getGridFSBucket(MongoClient mongoClient){
MongoDatabase database = mongoClient.getDatabase(db);
GridFSBucket bucket = GridFSBuckets.create(database);
return bucket;
}
}
2)测试代码
@Autowired
private GridFSBucket gridFSBucket;
/**
* 读取文件
* @throws IOException
*/
@Test
public void queryFile() throws IOException {
String fileId = "";
//1.根据id查询文件
GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId)));
assert gridFSFile != null;
//2.打开下载流对象
GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
//3.创建gridResource用于获取流对象
GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream);
//4.获取流中的数据
String s = IOUtils.toString(gridFsResource.getInputStream(),"UTF-8");
System.out.println(s);
}
删除文件
@Test
public void testDelFile(){
String id = "";
//根据文件id删除fs.files和fs.chunks中的记录
gridFsTemplate.delete(Query.query(Criteria.where("_id").is(id)));
}
3.3.4 模板存储
根据模板管理的流程,最终将模板信息存储到MongoDB的cms_template,将模板文件存储到GridFS中。
模板管理功能在
3.4 静态化测试
上边章节完成了数据模型和模板管理的测试,下边测试整个页面静态化的流程,流程如下:
1、填写页面DataUrl
在编辑cms页面信息界面填写DataUrl,将此字段保存到cms_page集合中。
2、静态化程序获取页面的DataUrl
3、静态化程序远程请求DataUrl获取数据模型。
4、静态化程序获取页面的模板信息
5、执行页面静态化
在CmsService中定义页面静态化方法,如下:
/**
* 页面静态化
* @param pageId
* @return
*/
@Override
public String getPageHtml(String pageId) {
//1.获取页面模型数据
Map model = getModelByPageId(pageId);
if (model == null){
//2.获取页面模型为空的时候抛出异常
ExceptionCast.cast(CmsCode.CMS_GENERATEHTML_DATAISNULL);
}
//3.获取页面模板
String templateContent = getTemplateByPageId(pageId);
if (StringUtils.isEmpty(templateContent)){
//4.页面模板为空的话就抛出异常
ExceptionCast.cast(CmsCode.CMS_GENERATEHTML_TEMPLATEISNULL);
}
//5.执行静态化
String html = generateHtml(templateContent,model);
if (StringUtils.isEmpty(html)){
ExceptionCast.cast(CmsCode.CMS_GENERATEHTML_HTMLISNULL);
}
return html;
}
整体代码框架如上所示,接下来就完成getModelByPageId,getTemplateByPageId,generateHtml
三个方法。
3.4.1 getModelByPageId
根据pageId查询静态化页面时所需的模型数据
/**
* 根据页面Id查询模型数据
* @param pageId
* @return
*/
private Map getModelByPageId(String pageId) {
//1.查询页面信息
CmsPage cmsPage = this.findById(pageId);
if (cmsPage == null){
//2.页面不存在
ExceptionCast.cast(CmsCode.CMS_PAGE_NOTEXISTS);
}
//3.取出dataUrl
String dataUrl = cmsPage.getDataUrl();
if (StringUtils.isEmpty(dataUrl)){
ExceptionCast.cast(CmsCode.CMS_GENERATEHTML_DATAISNULL);
}
ResponseEntity<Map> entity = this.restTemplate.getForEntity(dataUrl, Map.class);
return entity.getBody();
}
3.4.2 getTemplateByPageId
根据页面Id查询模板信息,获取到模板文件的id后,把模板文件转换成字符串返回。
/**
* 根据页面Id查询模板
* @param pageId
* @return
*/
private String getTemplateByPageId(String pageId) {
//1.查询页面信息
CmsPage cmsPage = this.findById(pageId);
if (cmsPage == null){
//2.页面不存在
ExceptionCast.cast(CmsCode.CMS_PAGE_NOTEXISTS);
}
//3.取出getTemplateId
String templateId = cmsPage.getTemplateId();
if (StringUtils.isEmpty(templateId)){
ExceptionCast.cast(CmsCode.CMS_GENERATEHTML_TEMPLATEISNULL);
}
//4.查询页面模板
Optional<CmsTemplate> optional = this.cmsTemplateRepository.findById(templateId);
if (optional.isPresent()){
CmsTemplate cmsTemplate = optional.get();
//5.模板文件Id
String templateFileId = cmsTemplate.getTemplateFileId();
//6.根据id查询文件
GridFSFile gridFSFile = this.gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(templateFileId)));
assert gridFSFile != null;
//7.打开下载流对象
GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
//8.创建gridResource用于获取流对象
GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream);
//9.获取流中的数据
try {
return IOUtils.toString(gridFsResource.getInputStream(),"UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
3.4.3 generateHtml
拿到模板和数据后,就可以进行页面的静态化了。
/**
* 页面静态化
* @param templateContent
* @param model
* @return
*/
private String generateHtml(String templateContent, Map model){
try {
//1.创建配置类
Configuration configuration = new Configuration(Configuration.getVersion());
//2.模板加载器
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
stringTemplateLoader.putTemplate("template", templateContent);
configuration.setTemplateLoader(stringTemplateLoader);
//4.得到模板
Template template = configuration.getTemplate("template", "utf-8");
//5.静态化
String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
return html;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
3.4.4 测试
3.4.4.1 新增测试页面

结果:

3.4.4.2 上传轮播图模板
GridFS上传index_banner.ftl文件:

结果:

3.4.4.3 修改轮播图模板中的templateFileId

将templateFileId字段的值修改为刚刚上传的文件id:5c9e0072dff2be4a682f5f47
修改后的结果:

3.4.4.4 页面静态化测试
编写测试类
package com.xuecheng.managecms;
import com.xuecheng.managecms.service.CmsService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @Author: 98050
* @Time: 2019-03-29 18:59
* @Feature: 页面静态化测试
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class PageStaticTest {
@Autowired
private CmsService cmsService;
@Test
public void pageStatic(){
cmsService.getPageHtml("5c9df9dadff2be27386be51b");
}
}
结果:

完成
四、页面预览
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
server:
port: 31001
spring:
application:
name: xc-service-manage-cms
data:
mongodb:
uri: mongodb://root:root@localhost:27017
database: xc_cms
freemarker:
cache: false #关闭模板缓存,方便测试
settings:
template_update_delay: 0 #检查模板更新延迟时间,设置为0表示立即检查,如果时间大于0会有缓存不方便进行模板测试
4.1.3 Service方法
在静态化测试中已经完成
4.1.4 Controller
直接调用service的静态化方法即可,将静态化内容通过response输出到浏览器显示
创建CmsPagePreviewController类,用于页面预览:
请求页面id,查询得到页面的模板信息、数据模型url,根据数据模型和模板生成静态化内容,并输出到浏览器。
package com.xuecheng.managecms.controller;
import com.xuecheng.framework.web.BaseController;
import com.xuecheng.managecms.service.CmsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
* @Author: 98050
* @Time: 2019-03-30 19:12
* @Feature: 页面预览
*/
@Controller
public class CmsPagePreviewController extends BaseController {
@Autowired
private CmsService cmsService;
@RequestMapping(value = "/cms/preview/{pageId}",method = RequestMethod.GET)
public void preview(@PathVariable("pageId") String pageId){
String pageHtml = this.cmsService.getPageHtml(pageId);
if (StringUtils.isNotEmpty(pageHtml)){
try {
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(pageHtml.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
测试:http://localhost:31001/cms/preview/5c9df9dadff2be27386be51b

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

重启nginx,测试:
http://www.xuecheng.com/cms/preview/5c9df9dadff2be27386be51b
4.2.2 添加“页面预览”连接

添加preview方法:
preview (pageId) {
window.open('http://www.xuecheng.com/cms/preview/' + pageId)
},
效果:

找到刚刚添加的页面:

点击预览
页面的静态化操作放在发布功能开发中,即静态页面上传到GridFS中,所以对前端页面进行调整:



被折叠的 条评论
为什么被折叠?



