[java] FreeMarkerUtil 模板工具

package com.22pig.util;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
*
* <b> FreeMarkerUtil 模板工具 </b>
*
* @author Stone
*
*/
public class FreeMarkerUtil {

/**
*
* 读取模板文件
*
* @author StoneLi
*
* @param fltFile
* flt文件名
* @param templatePath
* flt文件路径 src/template
* @param datas
* 数据集合
* @return
*/
public static String geneFileStr(String fltFile, String templatePath, Map<String, Object> datas) {
Configuration cfg = new Configuration();
try {
cfg.setClassForTemplateLoading(FreeMarkerUtil.class, templatePath);
Template template = cfg.getTemplate(fltFile, “UTF-8”);
template.setEncoding(“UTF-8”);
StringWriter out = new StringWriter();
template.process(datas, out);
out.flush();
out.close();
return out.getBuffer().toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

@SuppressWarnings(“unchecked”)
public static String geneFileStr(Class clazz,String fltFile, Map<String, Object> datas) {
String templatePath = “/” + clazz.getPackage().getName().replace(“.”, “/”);
return geneFileStr(fltFile,templatePath,datas);
}

/**
* 解析字符串模板,通用方法
*
* @param template 字符串模板
* @param model 数据
* @param configuration 配置
* @return 解析后内容
*/
public static String processStringTemplate(String template, Map<String, ?> datas, Configuration configuration){
String outStr = null;
try{
if (template == null) {
return null;
}
if (configuration == null) {
configuration = new Configuration();
}
StringWriter out = new StringWriter();
new Template(“template”, new StringReader(template), configuration).process(datas, out);
outStr = out.toString();
} catch (Exception e) {
e.printStackTrace();
}
return outStr;
}

}

留下评论