美文网首页
网站优化之使用Free marker静态化网站文章页

网站优化之使用Free marker静态化网站文章页

作者: 明月天 | 来源:发表于2019-11-30 19:23 被阅读0次

    博客做出来的时候就想要把一些栏目和文章页都静态化处理,当时没啥时间搞,就一直没去弄。但是最近的工作就是做网站,用cms快速搭出了几个网站,cms搭建网站是真的方便啊 如果没有需要二次开发实现的功能,那基本不需要写后端代码的。而且做出来的还不错,怪不得看很多博主都是用cms搭建的博客。 我是用的FreeCMS,展示层就有用Free Marker来做。 然后就参考这个cms的源码 把自己博客的文章页静态化了下。

    静态化主要是为了提高网页打开的速度,然后还有利于SEO,更容易被搜索引擎识别收录,而且比较稳定和安全。

    free marker静态化原理是用模板+数据模型=输出html网页。

    freemarker并不关心数据的来源,只是根据模板的内容,将数据模型在模板中显示并输出文件(通常为html,也可以生成其它格式的文本文件)
    原文链接:https://www.zjhuiwan.cn/info/20191130/1911300719136340000.html

    首先引入jar包

    Free marker的jar包和文档

    链接:https://pan.baidu.com/s/1GZNvnOT6wbb2S6646c7cSQ 密码:q0af

    maven依赖

        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.23</version>
        </dependency>
    

    代码

    根据模板文件和数据模型创建html的方法

    private void createHtml(String templetPath, String siteInfoPath, HashMap<String, Object> map) throws Exception {
            // ①创建配置对象(创建一个Configuration对象,直接new一个对象。构造方法的参数就是freemarker对于的版本号。)
            Configuration cfg = new Configuration(Configuration.getVersion());// 注意:这里需要传递一个版本
    
            // ②读取模板文件夹
            cfg.setDirectoryForTemplateLoading(new File(templetPath));// 设置要加载的模板文件的路径,这里的templetPath就是模板的路径webapp/templet/
            // ③设置模板的编码格式
            cfg.setDefaultEncoding("UTF-8");
    
            // ④获取模板对象
            Template template = cfg.getTemplate("info.html");// info.html是模板名称
    
            // ⑥将模板和数据模型合并 --> 输出模板,生成文件
            // 静态页面路径
            File htmlFile = new File(siteInfoPath); //siteInfoPath是静态化生成的html存放的路径,webapp/site/info/2019-11-30(文章日期)/文章id.html(根据自己的需要来设置)
            if (!htmlFile.getParentFile().exists()) {  
                htmlFile.getParentFile().mkdirs(); //文章不存在则创建
            }
            PrintWriter pw = new PrintWriter(htmlFile);
            template.process(map, pw);// 合并 map:数据模型 pw:输出流对象 map中存的是模板文件中需要的数据文章列表等,在模板文件中用${..}获取,可参考free marker文档
            pw.close();// 关闭流
        }
    

    静态化文章页的方法

    /**
         * 静态化文章页
         * 
         * @param articleId
         * @throws IOException
         */
        @RequestMapping({"/toCrea****"})
        public String toCreate****(HttpServletRequest request, Long articleId) throws Exception {
    
            LOGGER.info("静态化文章方法开始");
    
            //查询要静态化的文章信息
            Article article = new Article();
            article.setArticleId(articleId);
            Article articleDetail = articleService.selectByKeyWords(article);
            //文章发布的时间,用于将静态化的文章网页放在对应时间的文件夹中
            String articleTime = Tools.getStrDateTime(articleDetail.getCreationtime(), "yyyy-MM-dd");
    
            // 给文章添加访问路径(发布一篇文章后静态化该文章,静态化时将该文章的静态化后路径添加至数据库)
            String pageUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath() + "/site/info" + articleId + ".html";
            articleDetail.setPageUrl(pageUrl);
            articleService.upArticle(articleDetail);
    
            // 创建数据模型(这里使用map类型) --[数据模型可以是List、Map对象 注意:Map类型的key必须是String类型]
            HashMap<String, Object> map = new HashMap<>();
            map.put("contextPathNo", request.getSession().getServletContext().getContextPath());// 项目名称,用于生成后html页面的静态资源调用css,img等
            // 文章信息
             ......//其他信息代码省略。。。
    
             map.put("info", articleDetail);
            ......
    
                    //模板所在的路径
            String templetPath = request.getSession().getServletContext().getRealPath("/templet");
            //静态化生成的html路径
            String siteInfoPath = request.getSession().getServletContext()
                .getRealPath("/site/info/" + articleTime + "/" + articleId + ".html");
    
            createHtml(templetPath, siteInfoPath, map);
    
            return "success";
        }
    

    模板文件info.html(省略了很多代码,仅作为示例)

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>${info.articleTitle }</title>
    <link href="${contextPathNo}/css/details.css" rel="stylesheet">
    <script src="${contextPathNo}/js/jquery-1.7.2.min.js"></script>
    </head>
    <body>
            <!-- 文章信息 -->
            <h2 class="c_titile" style="font:'宋体', Arial, Helvetica, sans-serif;color: #756F71">${info.articleTitle}</h2>
            <p class="box_c" style="font: 12px '宋体', Arial, Helvetica, sans-serif;color: #756F71">
                <span class="d_time">发布时间:${info.creationtime?string('yyyy-MM-dd hh:mm') }</span>    <!-- ?string将date类型时间转为字符串显示-->
    
                <span>编辑:${info.articleAuthor}</span> 
                阅读:<span id='ajaxInfoClickSpan'><img src='${contextPathNo}/images/ajax-loader.gif'/></span><!-- 文章点击量 需要动态展示 -->
                <input type="hidden" value="${info.articleId?c}" id="articleIdinit"><!-- ?c将long类型文章id正常显示,不加?c会被,分割-->
    
            </p>
            <ul class="infos">${info.articleDetail }
            </ul>
    
            <!-- 其他的例如文章列表、判断等 -->
    
            <#if (info.parent==333)> <a class="n2" href="${contextPathNo}/toSharesss">程序人生</a> </#if>
                <!-- 非空判断 frm没有null-->
                        <#if upArticle??>
                <p>
                    上一篇:<a href="${contextPathNo}/toDetail}">${upArticle.articleTitle}</a>
                </p>
                </#if>
                <!-- 遍历列表,if else 。获取长度需要?使用.没用-->
                <ul class="rank">
                <#list newTimeArticleList as newList>
                    <#if (newList.articleTitle?length>16)>
                        <li><a href="${contextPathNo}/toDetail"
                            title="${newList.articleTitle }" target="_blank">${newList.articleTitle?substring(0,16)}...</a></li>
                    <#else>
                        <li><a href="${contextPathNo}/toDetail"
                            title="${newList.articleTitle }" target="_blank">${newList.articleTitle}</a></li>
                    </#if>
                </#list>
            </ul>
    
            <!-- 大概的模板,更多的内容参考文档-->
    </body>
    
    </html>
    

    这样就能根据模板来生成一个html静态网页了。

    需要注意的是,有些动态展示的内容 是不能直接静态化的,比如 文章的点击数和 右侧的最热文章,最新文章,底部的上一篇下一篇等。。。

    暂时没有的解决方式 我就用了ajax来加载的。。

    相关文章

      网友评论

          本文标题:网站优化之使用Free marker静态化网站文章页

          本文链接:https://www.haomeiwen.com/subject/ogxawctx.html