java解析freemarker文件或模板内容
freemarker文件一般是控制器返回后有freemarker控制器进行解析,在这里我们在java代码中解析freemarker文件
其他依赖包
网盘地址 提取码:i6o7
package com.my.utils;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.io.IOUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;
public final class FreemarkerParseUtils {
/**
* 不可实例化
*/
private FreemarkerParseUtils () {
}
/**
* 把ftl文件解析成html字符串内容
* @param templatePath ftl文件路径
* @param model 模型数据
* @return 解析后的html文件内容
*/
public static String parse(String templatePath, Map<String, Object> model) {
StringWriter stringWriter = null;
BufferedWriter writer = null;
try {
freemarker.template.Template template = SpringUtils.getBean("freeMarkerConfigurer", FreeMarkerConfigurer.class).getConfiguration().getTemplate(templatePath);
stringWriter = new StringWriter();
writer = new BufferedWriter(stringWriter);
template.process(model, writer);
writer.flush();
return stringWriter.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(writer);
IOUtils.closeQuietly(stringWriter);
}
return null;
}
/**
* 解析ftl文件内容
* @param content 原ftl模板文件内容
* @param model 模板文件数据
* @return 解析后的html文件内容
*/
public static String parseFtlContent(String content, Map<String, Object> model) {
// 获取配置
StringWriter out = new StringWriter();
try {
new Template("template", new StringReader(content), FreemarkerUtils.getFreeMarkerConfigurer().getConfiguration()).process(model, out);
} catch (TemplateException | IOException e) {
return "";
}
String htmlContent = out.toString();
if (out != null) {
try {
out.close();
} catch (IOException e) {
return "";
}
}
return htmlContent;
}
}