<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
@Slf4j
public class FreemarkerUtils {
private static final Configuration cfg;
private FreemarkerUtils() {
}
static {
cfg = new Configuration(Configuration.getVersion());
cfg.setDefaultEncoding("UTF-8");
// FreeMarker会默认格式化数字,这样设置不再格式化数字
cfg.setNumberFormat("#");
}
public static String processTemplate(String myTemplate, Map<String, Object> map) {
String result = null;
String name = "template";
try {
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
stringTemplateLoader.putTemplate(name, myTemplate);
cfg.setTemplateLoader(stringTemplateLoader);
Template template = cfg.getTemplate(name, "UTF-8");
StringWriter out = new StringWriter();
template.process(map, out);
out.flush();
result = out.toString();
out.close();
} catch (Exception e) {
log.error("FreemarkerUtils processTemplate error", e);
}
return result;
}
}
Map<String, Object> templateMap = new HashMap<>(8);
templateMap.put("statisticDate",123456);
String templateStr = "i am ${statisticDate}";
String str = FreemarkerUtils.processTemplate(templateStr, templateMap);
网友评论