zoukankan      html  css  js  c++  java
  • Day04_页面静态化

    页面静态化 页面预览

    1 页面静态化需求

    1、为什么要进行页面管理?

    本项目cms系统的功能就是根据运营需要,对门户等子系统的部分页面进行管理,从而实现快速根据用户需求修改 页面内容并上线的需求。
    

    2、如何修改页面的内容?

    在开发中修改页面内容是需要人工编写html及JS文件,CMS系统是通过程序自动化的对页面内容进行修改,通过 页面静态化技术生成html页面。
    

    3、如何对页面进行静态化?

    一个页面等于模板加数据,在添加页面的时候我们选择了页面的模板。
    页面静态化就是将页面模板和数据通过技术手段将二者合二为一,生成一个html网页文件。
    

    4、页面静态化及页面发布流程图如下:

    业务流程如下:

    1、获取模型数据
    2、制作模板
    3、对页面进行静态化
    4、将静态化生成的html页面存放文件系统中
    5、将存放在文件系统的html文件发布到服务器
    

    2 FreeMarker 研究

    参考链接:https://www.cnblogs.com/artwalker/p/13431741.html

    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;
        private Map mapValue;
        private String value;
    }
    

    上边的模型结构可以对照cms_config中的数据进行分析。

    其中,在mapValue 中可以存储一些复杂的数据模型内容。

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

    3.2.1.3 Dao

    定义CmsConfig的dao接口:

    package com.xuecheng.manage_cms.dao;
    
    import com.xuecheng.framework.domain.cms.CmsConfig;
    import org.springframework.data.mongodb.repository.MongoRepository;
    
    /**
     * @author HackerStar
     * @create 2020-08-04 13:22
     */
    public interface CmsConfigRepository extends MongoRepository<CmsConfig, String> {
    }
    
    3.2.1.4 Service

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

    package com.xuecheng.manage_cms.service;
    
    import com.xuecheng.framework.domain.cms.CmsConfig;
    import com.xuecheng.manage_cms.dao.CmsConfigRepository;
    import org.springframework.beans.factory.annotation.Autowired;
    
    import java.util.Optional;
    
    /**
     * @author HackerStar
     * @create 2020-08-04 13:24
     */
    @Service
    public class CmsConfigService {
        @Autowired
        CmsConfigRepository cmsConfigRepository;
    
        /**
         * 根据id查询配置管理信息
         * @param id
         * @return
         */
        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.5 Controller
    package com.xuecheng.manage_cms.web.controller;
    
    import com.xuecheng.api.cms.CmsConfigControllerApi;
    import com.xuecheng.framework.domain.cms.CmsConfig;
    import com.xuecheng.manage_cms.service.CmsConfigService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    
    /**
     * @author HackerStar
     * @create 2020-08-04 13:25
     */
    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

    package com.xuecheng.manage_cms;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.autoconfigure.domain.EntityScan;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
    import org.springframework.web.client.RestTemplate;
    
    /**
     * @author HackerStar
     * @create 2020-07-24 09:15
     */
    @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());
        }
    }
    

    3、测试RestTemplate

    根据url获取数据,并转为map格式。

     @Test
        public void testRestTemplate() {
            ResponseEntity<Map> forEntity = restTemplate().getForEntity("http://localhost:31001/cms/config/getmodel/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。

    2、数据模型为:

    数据模型的图片路径改成可以浏览的正确路径。

    3、编写模板

    在freemarker测试工程中新建模板index_banner.ftl。

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

    <!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>
        </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测试工程(FreemarkerController类下)编写一个方法测试轮播图模板,代码如下:

    @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.3 GridFS研究

    3.3.3.1 GridFS介绍

    GridFS是MongoDB提供的用于持久化存储文件的模块,CMS使用MongoDB存储数据,使用GridFS可以快速集成 开发。

    它的工作原理是:

    在GridFS存储文件是将文件分块存储,文件会按照256KB的大小分割成多个块进行存储,GridFS使用两个集合 (collection)存储文件,一个集合是chunks, 用于存储文件的二进制数据;一个集合是files,用于存储文件的元数据信息(文件名称、块大小、上传时间等信息)。
    从GridFS中读取文件要对文件的各各块进行组装、合并。
    详细参考:https://docs.mongodb.com/manual/core/gridfs/
    
    3.3.3.2 GridFS存取文件测试

    1、存文件

    使用GridFsTemplate存储文件测试代码:

    在测试工程的pom文件中添加依赖:

    <dependency>
    		<groupId>org.springframework.data</groupId>
    		<artifactId>spring-data-mongodb</artifactId>
    </dependency>
    

    向测试程序注入GridFsTemplate。

    package com.xuecheng.test.freemarker;
    
    import com.mongodb.client.gridfs.GridFSBucket;
    import com.mongodb.client.gridfs.GridFSDownloadStream;
    import com.mongodb.client.gridfs.model.GridFSFile;
    import org.apache.commons.io.IOUtils;
    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.core.query.Criteria;
    import org.springframework.data.mongodb.core.query.Query;
    import org.springframework.data.mongodb.gridfs.GridFsResource;
    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;
    import java.io.IOException;
    
    /**
     * @author Administrator
     * @version 1.0
     * @create 2018-09-12 18:11
     **/
    @SpringBootTest
    @RunWith(SpringRunner.class)
    public class GridFsTest {
    
        @Autowired
        GridFsTemplate gridFsTemplate;
    
        //存文件
        @Test
        public void testStore() throws FileNotFoundException {
            //定义file
            File file =new File("/Users/XinxingWang/Development/Java/IDEA_Project/xcEduCode/test-freemarker/src/test/resources/templates/gridFS/index_banner.html");
            //定义fileInputStream
            FileInputStream fileInputStream = new FileInputStream(file);
            ObjectId objectId = gridFsTemplate.store(fileInputStream, "index_banner.ftl");
            System.out.println(objectId);
        }
    }
    

    存储原理说明:

    文件存储成功得到一个文件id。
    此文件id是fs.files集合中的主键。
    可以通过文件id查询fs.chunks表中的记录,得到文件的内容。
    

    2、读取文件

    1)在config包中定义Mongodb的配置类,如下:

    GridFSBucket用于打开下载流对象

    package com.xuecheng.test.freemarker.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 HackerStar
     * @create 2020-08-04 15:36
     */
    @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)测试代码如下

     @Test
        public void queryFile() throws IOException {
    
            String fileId = "5b091f93c5e9b7070c94a2b9";
    
            GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId)));
            GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
            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("5b091f93c5e9b7070c94a2b9")));
        }
    

    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中定义页面静态化方法,如下:

    package com.xuecheng.manage_cms.service;
    
    import com.mongodb.client.gridfs.GridFSBucket;
    import com.mongodb.client.gridfs.GridFSDownloadStream;
    import com.mongodb.client.gridfs.model.GridFSFile;
    import com.xuecheng.framework.domain.cms.CmsPage;
    import com.xuecheng.framework.domain.cms.CmsTemplate;
    import com.xuecheng.framework.domain.cms.request.QueryPageRequest;
    import com.xuecheng.framework.domain.cms.response.CmsCode;
    import com.xuecheng.framework.domain.cms.response.CmsPageResult;
    import com.xuecheng.framework.exception.ExceptionCast;
    import com.xuecheng.framework.model.response.CommonCode;
    import com.xuecheng.framework.model.response.QueryResponseResult;
    import com.xuecheng.framework.model.response.QueryResult;
    import com.xuecheng.framework.model.response.ResponseResult;
    import com.xuecheng.manage_cms.dao.CmsConfigRepository;
    import com.xuecheng.manage_cms.dao.CmsPageRepository;
    import com.xuecheng.manage_cms.dao.CmsTemplateRepository;
    import freemarker.cache.StringTemplateLoader;
    import freemarker.template.Configuration;
    import freemarker.template.Template;
    import org.apache.commons.io.IOUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.domain.*;
    import org.springframework.data.mongodb.core.query.Criteria;
    import org.springframework.data.mongodb.core.query.Query;
    import org.springframework.data.mongodb.gridfs.GridFsResource;
    import org.springframework.data.mongodb.gridfs.GridFsTemplate;
    import org.springframework.http.ResponseEntity;
    import org.springframework.stereotype.Service;
    import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
    import org.springframework.web.client.RestTemplate;
    
    import java.io.IOException;
    import java.util.Map;
    import java.util.Optional;
    
    /**
     * @author HackerStar
     * @create 2020-07-24 10:59
     */
    @Service
    public class PageService {
        @Autowired
        CmsPageRepository cmsPageRepository;
    
        @Autowired
        CmsConfigRepository cmsConfigRepository;
    
        @Autowired
        RestTemplate restTemplate;
    
        @Autowired
        CmsTemplateRepository cmsTemplateRepository;
    
        @Autowired
        GridFsTemplate gridFsTemplate;
    
        @Autowired
        GridFSBucket gridFSBucket;
    
        /**
         * 页面列表分页查询
         * @param page  当前页码
         * @param size  页面显示个数
         * @param queryPageRequest  查询条件
         * @return  页面列表
         */
        public QueryResponseResult findList(int page, int size, QueryPageRequest queryPageRequest) {
            if (queryPageRequest == null) {
                queryPageRequest = new QueryPageRequest();
            }
            //条件匹配器
            //页面名称模糊查询,需要自定义字符串的匹配器实现模糊查询
            ExampleMatcher exampleMatcher = ExampleMatcher.matching().withMatcher("pageAliase", ExampleMatcher.GenericPropertyMatchers.contains());
            //条件值
            CmsPage cmsPage = new CmsPage();
            //站点id
            if(StringUtils.isNotEmpty(queryPageRequest.getSiteId())){
                cmsPage.setSiteId(queryPageRequest.getSiteId());
            }
            //页面别名
            if(StringUtils.isNotEmpty(queryPageRequest.getPageAliase())) {
                cmsPage.setPageAliase(queryPageRequest.getPageAliase());
            }
            //创建条件实例
            Example<CmsPage> example = Example.of(cmsPage, exampleMatcher);
            if (page <= 0) {
                page = 1;
            }
            //页码
            page = page - 1;
            if (size <= 0) {
                size = 20;
            }
            //分页对象
            Pageable pageable = PageRequest.of(page, size);
    
            //分页查询
            Page<CmsPage> all = cmsPageRepository.findAll(example,pageable);
            QueryResult<CmsPage> cmsPageQueryResult = new QueryResult<CmsPage>();
            cmsPageQueryResult.setList(all.getContent());
            cmsPageQueryResult.setTotal(all.getTotalElements());
            return new QueryResponseResult(CommonCode.SUCCESS, cmsPageQueryResult);
        }
    
        /**
         * 添加页面
         */
        public CmsPageResult add(CmsPage cmsPage) {
            //校验cmsPage是否为空
            if(cmsPage == null){
                //抛出异常,非法请求
                //......
            }
            //校验页面是否存在,根据页面名称、站点Id、页面webpath查询
            CmsPage cmsPage1 = cmsPageRepository.findByPageNameAndSiteIdAndPageWebPath(cmsPage.getPageName(), cmsPage.getSiteId(), cmsPage.getPageWebPath());
            //校验页面是否存在,已存在则抛出异常
            if(cmsPage1 != null) {
                //抛出异常,非法请求
                //......
                ExceptionCast.cast(CmsCode.CMS_ADDPAGE_EXISTSNAME);
            }
            cmsPage.setPageId(null);//添加页面主键由spring data 自动生成
            cmsPageRepository.save(cmsPage);
            //返回结果
            return  new CmsPageResult(CommonCode.SUCCESS, cmsPage);
        }
    
        /**
         * 根据ID查询页面
         */
        public CmsPage getById(String id) {
            Optional<CmsPage> optional = cmsPageRepository.findById(id);
            if (optional.isPresent()) {
                return optional.get();
            }
            //返回空
            return null;
        }
    
        /**
         * 更新页面信息
         */
        public CmsPageResult update(String id, CmsPage cmsPage) {
            //根据id查询页面信息
            CmsPage one = this.getById(id);
            if (one != null) {
                //更新模板id
                one.setTemplateId(cmsPage.getTemplateId());
                //更新所属站点
                one.setSiteId(cmsPage.getSiteId());
                //更新页面别名
                one.setPageAliase(cmsPage.getPageAliase());
                //更新页面名称
                one.setPageName(cmsPage.getPageName());
                //更新访问路径
                one.setPageWebPath(cmsPage.getPageWebPath());
                //更新物理路径
                one.setPagePhysicalPath(cmsPage.getPagePhysicalPath());
                //更新dataUrl
                one.setDataUrl(cmsPage.getDataUrl());
                //执行更新
                CmsPage save = cmsPageRepository.save(one);
                if (save != null) {
                    // 返回成功
                    CmsPageResult cmsPageResult = new CmsPageResult(CommonCode.SUCCESS, save);
                    return cmsPageResult;
                }
            }
            // 返回失败
            return new CmsPageResult(CommonCode.FAIL, null);
        }
    
        /**
         * 删除页面
         * @param id
         * @return
         */
        public ResponseResult delete(String id) {
            CmsPage one = this.getById(id);
            if(one != null) {
                //删除页面
                cmsPageRepository.deleteById(id);
                return new ResponseResult(CommonCode.SUCCESS);
            }
            return new ResponseResult(CommonCode.FAIL);
        }
    
        //页面静态化方法
        /**
         * 静态化程序获取页面的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 String generateHtml(String templateContent, Map model ){
            //创建配置对象
            Configuration configuration = new Configuration(Configuration.getVersion());
            //创建模板加载器
            StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
            stringTemplateLoader.putTemplate("template",templateContent);
            //向configuration配置模板加载器
            configuration.setTemplateLoader(stringTemplateLoader);
            //获取模板
            try {
                Template template = configuration.getTemplate("template");
                //调用api进行静态化
                String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
                return content;
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return null;
        }
    
        //获取页面的模板信息
        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(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;
    
        }
    
        //获取数据模型
        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_DATAURLISNULL);
            }
            //通过restTemplate请求dataUrl获取数据
            ResponseEntity<Map> forEntity = restTemplate.getForEntity(dataUrl, Map.class);
            Map body = forEntity.getBody();
            return body;
    
        }
    }
    

    创建config包及其config类,以及在dao中添加CmsTemplateRepository类。

    public interface CmsTemplateRepository extends MongoRepository<CmsTemplate,String> {
    }
    

    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

    server:
      port: 31001
    spring:
      application:
        name: sc-service-manage-cms
      data:
        mongodb:
          uri: mongodb://localhost:27017
          database: xc_cms
      freemarker:
        cache: false
        settings:
         template_update_delay: 0
    

    4.1.3 Service

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

    4.1.4 Controller

    调用service的静态化方法,将静态化内容通过response输出到浏览器显示。

    创建CmsPagePreviewController类,用于页面预览:

    请求页面id,查询得到页面的模板信息、数据模型url,根据模板和数据生成静态化内容,并输出到浏览器。

    package com.xuecheng.manage_cms.web.controller;
    
    import com.xuecheng.framework.web.BaseController;
    import com.xuecheng.manage_cms.service.PageService;
    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;
    
    /**
     * @author Administrator
     * @version 1.0
     * @create 2018-09-15 16:20
     **/
    @Controller
    public class CmsPagePreviewController extends BaseController {
    
        @Autowired
        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"));
    
        }
    }
    

    4.2 页面预览测试

    4.2.1 配置Nginx代理

    为了通过nginx请求静态资源(css、图片等),通过nginx代理进行页面预览。

    在www.xuecheng.com虚拟主机配置:

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

    重新加载nginx 配置文件。

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

    重新加载nginx配置文件。

    从cms_page找一个页面进行测试。注意:页面配置一定要正确,需设置正确的模板id和dataUrl。

    5a795ac7dd573c04508f3a56:轮播图页面的id

    使用之前做过的管理员修改页面内容给轮播图添加dataUrl:http://localhost:31001/cms/config/getmodel/5a791725dd573c3574ee333f

    运行GridFS存文件测试程序,将之前做的index_banner.html文件存储到数据库fs.files

    因为数据库客户端使用的DataGrip,只能读取数据库信息,不能手动更改数据库信息,所以手动将cms_template.json中轮播图的templateFileId修改为5f2a0331085c8bdc83e77bc8

    在浏览器打开:http://www.xuecheng.com/cms/preview/5a795ac7dd573c04508f3a56

    4.2.2 添加“页面预览”链接

    在页面列表添加“页面预览”链接,修改page_list.vue:

    <el-table-column label="操作" width="80">
            <template slot-scope="page">
              <el-button size="small" type="text" @click="edit(page.row.pageId)">编辑</el-button>
              <el-button size="small" type="text" @click="del(page.row.pageId)">删除</el-button>
              <el-button @click="preview(page.row.pageId)" type="text" size="small">页面预览</el-button>
            </template>
    </el-table-column>
    

    添加preview方法:

    preview(pageId) {
        window.open("http://www.xuecheng.com/cms/preview/"+pageId);
    }
    

    效果:

    点击轮播图页面的“页面预览”,预览页面效果。

  • 相关阅读:
    Java-JUC(十二):有3个线程。线程A和线程B并行执行,线程C需要A和B执行完成后才能执行。可以怎么实现?
    Spark2.x(五十九):yarn-cluster模式提交Spark任务,如何关闭client进程?
    Spark2.x(五十七):User capacity has reached its maximum limit(用户容量已达到最大限制)
    Spark2.x(五十六):Queue's AM resource limit exceeded.
    Java-Maven(十二):idea多项目:common module进行compiler和install正常,运行domain-perf module提示:Could not resolve dependencies for project
    Linux Shell:Map的用法
    Spark2.x(五十五):在spark structured streaming下sink file(parquet,csv等),正常运行一段时间后:清理掉checkpoint,重新启动app,无法sink记录(file)到hdfs。
    Linux Shell:根据指定的文件列表 或 map配置,进行文件位置转移
    Java-Maven(十一):Maven 项目出现pom.xml错误:Plugin execution not covered by lifecycle configuration: org.apache.maven.plugins:maven-compiler-plugin
    Spark2.x(五十四):在spark structured streaming下测试ds.selectExpr(),当返回列多时出现卡死问题。
  • 原文地址:https://www.cnblogs.com/artwalker/p/13438242.html
Copyright © 2011-2022 走看看