package com.sipai.controller.base; import java.io.BufferedWriter; import java.io.File; import java.io.StringWriter; import java.util.Map; import freemarker.template.Configuration; import freemarker.template.Template; public class HtmlGenerator { /** * Generate html string. * * @param template the name of freemarker teamlate. * @param variables the data of teamlate. * @return htmlStr * @throws Exception */ public static String generate(String templateFile, Map variables) throws Exception{ File file = new File(templateFile); if(!file.exists()) throw new Exception("模板文件不存在:"+templateFile); String templateDir = file.getParentFile().getPath(); String templateName =file.getName(); Configuration config = FreemarkerConfiguration.getConfiguation(); //用于解决前端报空指针问题--> config.setClassicCompatible(true); config.setDirectoryForTemplateLoading(new File(templateDir)); Template tp = config.getTemplate(templateName); StringWriter stringWriter = new StringWriter(); BufferedWriter writer = new BufferedWriter(stringWriter); tp.setEncoding("UTF-8"); tp.process(variables, writer); String htmlStr = stringWriter.toString(); writer.flush(); writer.close(); return htmlStr; } }