1. getTemplate()方法分别用来获取模板,以及配置好参数的模板 /** * 根据TransCode读取模板,模板中的参数被处理 * @param transCode * @param params * @return */ public String getTemplate(String transCode, Map params) { Assert.hasLength(transCode, "TransCode不能为空!"); Assert.notNull(params); Template template = this.getTemplate(transCode); StringWriter writer = new StringWriter(); try { template.process(params, writer); } catch (TemplateException e) { log.error(e.getMessage()); } catch (IOException e) { log.error(e.getMessage()); } String rv = writer.toString(); try{ rv = xmlTrimByPattern(rv); }catch(Exception e){ log.error(e.getMessage()); } return rv; } /** * 根据TransCode读取模板,模板中的参数没有被处理 * @param transCode * @return */ public Template getTemplate(String transCode) { Assert.hasLength(transCode, "TransCode不能为空!"); Map cm = CgsManager.getInstance().getTemplateMap(); if(cm.isEmpty()){ System.out.println("缓存加载失败,请联系管理员"); } String fileName = transCode + ".xml"; String strloader = null; if(cm.containsKey(fileName)){ strloader = cm.get(fileName).toString(); }else{ System.out.println("不存在模板!"); return null; } Template template = null; Configuration cfg = new Configuration(); try { cfg.setTemplateLoader(new StringTemplateLoader(strloader)); template = cfg.getTemplate(""); } catch (IOException e) { log.error(e.getMessage()); } return template; } 2. StringTemplateLoader类 package cgs.util; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import freemarker.cache.TemplateLoader; public class StringTemplateLoader implements TemplateLoader { private static final String DEFAULT_TEMPLATE_KEY = "_default_template_key"; private Map templates = new HashMap(); public StringTemplateLoader(String defaultTemplate) { if (defaultTemplate != null && !defaultTemplate.equals("")) { templates.put(DEFAULT_TEMPLATE_KEY, defaultTemplate); } } public void AddTemplate(String name, String template) { if (name == null || template == null || name.equals("") || template.equals("")) { return; } if (!templates.containsKey(name)) { templates.put(name, template); } } public void closeTemplateSource(Object templateSource) throws IOException { } public Object findTemplateSource(String name) throws IOException { if (name == null || name.equals("")) { name = DEFAULT_TEMPLATE_KEY; } return templates.get(name); } public long getLastModified(Object templateSource) { return 0; } public Reader getReader(Object templateSource, String encoding) throws IOException { return new StringReader((String) templateSource); } }