springboot 通過freemarker生成html
阿新 • • 發佈:2021-01-13
package com.saoft.fastdemo.gen; import freemarker.cache.ClassTemplateLoader; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import java.io.IOException; import java.io.StringWriter; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; public class FreemarkerDemo { public static void main(String[] args) throws IOException, TemplateException { /*初始化freemarker模板*/ Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); configuration.setDefaultEncoding(Charset.forName("UTF-8").name()); //這裡的ClassTemplateLoader 的basePackagePath 如果是 / 開頭就是絕對路徑。如果不是/ 開頭就是相對於 //com.saoft.fastdemo.gen.FreemarkerDemo.java 這個類的相對路徑,會以com.saoft.fastdemo.gen這個目錄開始找 //FileTemplateLoader configuration.setTemplateLoader(new ClassTemplateLoader(FreemarkerDemo.class,"/templates/")); //獲取模板 Template template = configuration.getTemplate("ssm/demo.ftl"); //需要注入的資料 Map<String, Object> dataMap = new HashMap<>(); dataMap.put("testKey", "This is key"); //輸出位置 這裡用字串輸出,如果要輸出檔案自行替換 StringWriter writer = new StringWriter(); template.process(dataMap, writer); System.out.println(writer.getBuffer()); } }