阶段5 3.微服务项目【学成在线】_day04 页面静态化_11-freemarker静态化测试-基于模板字符串静态化

再定义一个测试方法


把拿到的字符串变成模板



加载器设置好了以后,

加一个断点来测试


生成模板文件

上面这种方式很灵活。
 

最终代码

@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 map=getMap();
        //静态化
        String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        InputStream inputStream = IOUtils.toInputStream(content);
        FileOutputStream outputStream = new FileOutputStream(new File("d:/test1.html"));

        //输出文件
        IOUtils.copy(inputStream,outputStream);
        inputStream.close();
        outputStream.close();

    }

 

test1.html

<html>
    <head></head>
    <body>
    名称:黑马程序员
    </body>
</html>

 



 

posted @ 2019-09-26 13:46  高山-景行  阅读(213)  评论(0编辑  收藏  举报