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

来源:互联网 发布:mac关闭spotlight搜索 编辑:程序博客网 时间:2024/04/17 01:42
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;}// testpublic 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"}

原创粉丝点击