把拿到的字符串变成模板

加载器设置好了以后,

加一个断点来测试

生成模板文件

上面这种方式很灵活。
 

最终代码

@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>

 



 

相关文章:

  • 2022-01-15
  • 2021-06-06
  • 2021-12-13
  • 2021-09-17
  • 2021-10-25
  • 2022-01-20
  • 2021-11-27
  • 2021-11-24
猜你喜欢
  • 2022-01-09
  • 2021-12-23
  • 2021-08-16
  • 2022-01-07
  • 2022-02-15
  • 2021-06-02
  • 2022-01-18
相关资源
相似解决方案