使用Freemarker替换Java字符串定义变量



使用Freemarker替换Java字符串定义变量方法。

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.IOException;
import java.io.StringWriter;

public static String freemarkerProcess(Map input, String templateStr) {
StringTemplateLoader stringLoader = new StringTemplateLoader();
String template = “content”;
stringLoader.putTemplate(template, templateStr);
Configuration cfg = new Configuration();
cfg.setTemplateLoader(stringLoader);
try {
Template templateCon = cfg.getTemplate(template);
StringWriter writer = new StringWriter();
templateCon.process(input, writer);
return writer.toString();
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
return null;
}

// test
public static void main(String[] args) {
String template = “你好${姓名!’未知’},今天是${date?string(‘yyyy-MM-dd’)}”; //变量参考freemarker语法
Map m = new HashMap();
m.put(“姓名”, “管理员”);
m.put(“date”, new Date());
System.out.println(freemarkerProcess(m, template)); //”你好管理员,今天是2013-09-11″
}