1. 页面静态化需求
1. 为什么对页面进行管理
本项目对cms的定位是对页面进行管理,对那些由于经营需要(首页的广告、门户页面样式)而需要快速上线的功能页面进行管理
2. 如何进行页面管理
通过人工开发来编写HTML页面可以实现,如果采用cms系统就可以实现由cms自动化对页面进行更新,自动采用静态化的技术生成HTML页面,快速上线。
3. 如何对页面进行静态化
采用页面模板+数据=输出HTML页面的技术实现静态化
4. 静态化的HTML页面存放哪里
生成的静态化的页面,由cms程序自动发布到服务器(门户服务器、其他)中,实现页面的快速上线。
2. 页面静态化
1. 页面静态化流程
模板+数据模型=输出。如何获取页面的数据模型?
CMS管理了各种页面,CMS对页面进行静态化时需要数据模型,但是CMS并不知道每个页面的数据模型的具体内
容,它只管执行静态化程序便可对页面进行静态化,所以CMS静态化程序需要通过一种通用的方法来获取数据模
型
在编辑页面信息时指定一个DataUrl,此DataUrl便是获取数据模型的Url,它基于Http方式,CMS对页面进行静态
化时会从页面信息中读取DataUrl,通过Http远程调用的方法请求DataUrl获取数据模型
管理员怎么知道DataUrl的内容呢?
轮播图页面,它的DataUrl由开发轮播图管理的程序员提供 ;精品课程推荐页面,它的DataUrl由精品课程推荐的程序员提供;课程详情页面,它的DataUrl由课程管理的程序员提供。
页面静态化流程如下图:
- 静态化程序首先读取页面获取DataUrl。
- 静态化程序远程请求DataUrl得到数据模型。
- 获取页面模板。
- 执行页面静态化。
2. 数据模型
1. 轮播图DataUrl接口
1. 需求分析
CMS中有轮播图管理、精品课程推荐的功能,以轮播图管理为例说明:轮播图管理是通过可视化的操作界面由管理
员指定轮播图图片地址,最后将轮播图图片地址保存在cms_config集合中
针对首页的轮播图信息、精品推荐等信息的获取统一提供一个Url供静态化程序调用,这样我们就知道了轮播图页
面、精品课程推荐页面的DataUrl,管理在页面配置中将此Url配置在页面信息中
本小节开发一个查询轮播图、精品推荐信息的接口,此接口供静态化程序调用获取数据模型。
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. dao
定义CmsConfig的dao接口
public interface CmsConfigRepository extends MongoRepository<CmsConfig,String> {
}
4. service
定义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;
} r
eturn null;
}
}
5. Controller
@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);
}
}
6. 测试
3. 远程请求接口
SpringMVC提供 RestTemplate请求http接口,RestTemplate的底层可以使用第三方的http客户端工具实现http 的
请求,常用的http客户端工具有Apache HttpClient、OkHttpClient等,本项目使用OkHttpClient完成http请求
- 添加依赖
- 配置RestTemplate 在SpringBoot启动类中配置RestTemplate
@SpringBootApplication
@EntityScan("com.xuecheng.framework.domain.cms")//扫描实体类
@ComponentScan(basePackages = {"com.xuecheng.api"})//扫描接口
@ComponentScan(basePackages = {"com.xuecheng.manage_cms"})//扫描自己的
@ComponentScan(basePackages = {"com.xuecheng.framework"})//扫描common工程的类
public class ManageCmsApplication {
public static void main(String[] args) {
SpringApplication.run(ManageCmsApplication.class,args);
}
@Bean
public RestTemplate restTemplate(){
return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
}
}
- 测试RestTemplate
根据url获取数据,并转换为map格式
@SpringBootTest
@RunWith(SpringRunner.class)
public class RestTemplateTest {
@Autowired
private RestTemplate restTemplate;
@Test
public void testRestTemplate(){
ResponseEntity<Map> forEntity = restTemplate.getForEntity("http://localhost:31001/getmodel/5a791725dd573c3574ee333f", Map.class);
Map body = forEntity.getBody();
System.out.println(body);
}
}
3. 模板管理
1. 模板管理业务流程
cms提供模板管理功能,业务流程如下
- 要增加新模板首先需要制作模板,模板的内容就是Freemarker ftl模板内容。
- 通过模板管理模块功能新增模板、修改模板、删除模板
- 模板信息存储在MongoDB数据库,其中模板信息存储在cms_template集合中,模板文件存储在GridFS文件系
统中
下边是一个模板的例子
{
"_id" : ObjectId("5a962b52b00ffc514038faf7"),
"_class" : "com.xuecheng.framework.domain.cms.CmsTemplate",
"siteId" : "5a751fab6abb5044e0d19ea1",
"templateName" : "首页",
"templateParameter" : "",
"templateFileId" : "5a962b52b00ffc514038faf5"
}
其中templateFileId是模板文件的ID,此ID对应GridFS文件系统中文件ID
2. 模板制作
1. 编写模板文件
- 轮播图页面原型
在门户的静态工程目录有轮播图的静态页面,路径是:/include/index_banner.html
- 数据模型通过http获取数据,将图片路径改为可以浏览的正确路径
- 编写模板 在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 class="indicators"></div>
<div>图片文件损坏</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. 模板测试
编写方法测试轮播图模板
@Autowired
private RestTemplate restTemplate;
@RequestMapping("/banner")
public String index_banner(Map<String,Object> map){
// 使用restTemplate请求轮播图的模型数据
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";
}
3. GridFS研究
1. 介绍
GridFS是MongoDB提供的用于持久化存储文件的模块,CMS使用MongoDB存储数据,使用GridFS可以快速集成
开发
它的工作原理是: 在GridFS存储文件是将文件分块存储,文件会按照256KB的大小分割成多个块进行存储,GridFS使用两个集合(collection)存储文件,一个集合是chunks, 用于存储文件的二进制数据;一个集合是files,用于存储文件的元数据信息(文件名称、块大小、上传时间等信息)。
从GridFS中读取文件要对文件的各各块进行组装、合并。
2. GridFS存取文件测试
@SpringBootTest
@RunWith(SpringRunner.class)
public class GridFSTest {
@Autowired
private GridFsTemplate gridFsTemplate;
@Autowired
private GridFSBucket gridFSBucket;
// 存文件5cfcd43b5ed156408c2a03c0
@Test
public void testGridFSTemplate() throws FileNotFoundException {
// 定义file
File file = new File("e:/index_banner.ftl");
// 定义fileInputStream
FileInputStream fileInputStream = new FileInputStream(file);
ObjectId objectId = gridFsTemplate.store(fileInputStream, "index_banner.ftl");
System.out.println(objectId);
}
// 取文件
@Test
public void queryFile() throws IOException {
// 根据文件id查询文件
GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is("5cfcd43b5ed156408c2a03c0")));
// 打开下载流对象
GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
// 创建GridFSResource对象,获取流
GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream);
// 从流中取数据
String content = IOUtils.toString(gridFsResource.getInputStream(), "utf-8");
System.out.println(content);
}
}
- 存文件
文件存储成功得到一个文件id 此文件id是fs.files集合中的主键 可以通过文件id查询fs.chunks表中的记录,得到文件的内容。
- 读取文件
在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;
}
}
4. 模板存储
根据模板管理的流程,最终将模板信息存储到MongoDB的cms_template中,将模板文件存储到GridFS中
手动向cms_template及GridFS中存储模板,增删改都是直接在Studio 3T 进行
4. 静态化测试
1、填写页面DataUrl
在编辑cms页面信息界面填写DataUrl,将此字段保存到cms_page集合中。
2、静态化程序获取页面的DataUrl
3、静态化程序远程请求DataUrl获取数据模型。
4、静态化程序获取页面的模板信息
5、执行页面静态化
1. 填写页面dataUrl
修改页面管理模板代码,实现编辑页面DataUrl。 此地址由程序员提供给系统管理员
2. 静态化程序
在pageService中定义页面静态化方法
/**
* 页面静态化方法:
* 静态化程序获取页面的DataUrl
* 静态化程序远程请求DataUrl获取数据模型
* 静态化程序获取页面的模板信息
* 执行页面静态化
*/
public String getPageHtml(String pageId){
// 获取数据模型
Map model = getModelByPageId(pageId);
if(model == null){
// 数据模型获取不到
ExceptionCast.cast(CmsCode.CMS_GENERATEHTML_DATAISNULL);
}
// 获取页面模板信息
String template = getTemplateByPageId(pageId);
if(StringUtils.isEmpty(template)){
ExceptionCast.cast(CmsCode.CMS_GENERATEHTML_TEMPLATEISNULL);
}
// 执行静态化
String html = generateHtml(template, model);
return html;
}
// 获取数据模型
private 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)){
// 页面dataUrl为空
ExceptionCast.cast(CmsCode.CMS_GENERATEHTML_DATAISNULL);
}
// 通过restTemplate请求dataUrl获取数据
ResponseEntity<Map> forEntity = restTemplate.getForEntity(dataUrl, Map.class);
Map body = forEntity.getBody();
return body;
}
@Autowired
private CmsTemplateRepository cmsTemplateRepository;
@Autowired
private GridFsTemplate gridFsTemplate;
@Autowired
private GridFSBucket gridFSBucket;
// 获取页面模板信息
private String getTemplateByPageId(String pageId){
// 取出页面的信息
CmsPage cmsPage = this.getById(pageId);
if(cmsPage==null){
// 页面不存在
ExceptionCast.cast(CmsCode.CMS_PAGE_NOTEXISTS);
}
// 获取页面的模板id
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();
// 从GridFS中取模板文件内容
// 根据文件id查询文件
GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is("5cfcd43b5ed156408c2a03c0")));
// 打开下载流对象
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;
}
// 执行静态化
private String generateHtml(String templateContent,Map model){
// 创建配置对象
Configuration configuration = new Configuration(Configuration.getVersion());
// 使用模板加载器变为模板
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
stringTemplateLoader.putTemplate("template",templateContent);
// 在配置中设置模板加载器
configuration.setTemplateLoader(stringTemplateLoader);
// 获取模板内容
try {
Template template = configuration.getTemplate("template");
// 调用api进行静态化
String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
return content;
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
return null;
}
单元测试
4. 页面预览
1. 页面预览开发
1. 需求分析
页面在发布前增加页面预览的步骤,方便用户检查页面内容是否正确。
1、用户进入cms前端,点击“页面预览”在浏览器请求cms页面预览链接。
2、cms根据页面id查询DataUrl并远程请求DataUrl获取数据模型。
3、cms根据页面id查询页面模板内容
4、cms执行页面静态化。
5、cms将静态化内容响应给浏览器。
6、在浏览器展示页面内容,实现页面预览的功能。
2. 搭建环境
在cms服务需要集成freemarker 在application.yml配置freemarker
server:
port: 31001
spring:
application:
name: xc-service-manage-cms
data:
mongodb:
uri: mongodb://root:123@localhost:27017
database: xc_cms
freemarker:
cache: false # 关闭缓存,方便测试
settings:
template_update_delay: 0
3. service
静态化方法已经实现
4. controller
调用service的静态化方法,将静态化内容通过response输出到浏览器显示
创建CmsPagePreviewController类,用于页面预览
请求页面id,查询得到页面的模板信息、数据模型url,根据模板和数据生成静态化内容,并输出到浏览器
@Controller
public class CmsPagePreviewController extends BaseController {
@Autowired
private PageService pageService;
// 页面预览
@RequestMapping(value = "/cms/preview/{pageId}",method = RequestMethod.GET)
public void preview(@PathVariable("pageId") String pageId) throws IOException {
// 执行静态化
String pageHtml = pageService.getPageHtml(pageId);
// 通过response对象将内容输出
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(pageHtml.getBytes("utf-8"));
}
}
2. 预览测试
1. 配置nginx代理
虚拟主机配置
#页面预览
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。
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)
},