springboot集成freemarker静态模板

springboot集成freemarker静态模板

1、导入依赖jar包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

2、templates文件夹下创建静态模板test.flt

3、创建test实体类:

public class TestBo {
          
   

    private Integer id;
    private String name;
    private String info;
    private BigDecimal price;
}

4、main方法运行

public static void main(String[] args) {
          
   
    //创建一个freemarker的上下文环境配置类
    Configuration configuration;
    configuration = new Configuration();
    //设置编码格式
    configuration.setDefaultEncoding("UTF-8");

    try {
          
   
        //设置本地模板所在文件夹位置     仅在main方法中测试使用
        configuration.setDirectoryForTemplateLoading(new File("C:\Users\86177\Desktop\jk优选\springboot-freemarker\src\main\resources\templates"));
        //获取对应的模板文件     参数为模板文件名
        Template template = configuration.getTemplate("test.flt");

        //new对象
        TestBo testBo = new TestBo();
        testBo.setId(1);
        testBo.setName("王琦");
        testBo.setInfo("程序猿");
        testBo.setPrice(new BigDecimal(88.88));

        //创建一个FileWriter    写对象 把生成的文件写到对应的位置
        FileWriter fileWriter = new FileWriter(new File("E:/"+testBo.getId()+".html"));
        //生成静态网页
        template.process(testBo,fileWriter);
    } catch (IOException e) {
          
   
        e.printStackTrace();
    } catch (TemplateException e) {
          
   
        e.printStackTrace();
    }

}
经验分享 程序员 微信小程序 职场和发展