FreeMarker的使用
引入的jar包:
1 import freemarker.core.Environment; 2 import freemarker.core.TemplateElement; 3 import freemarker.ext.beans.StringModel; 4 import freemarker.template.Configuration; 5 import freemarker.template.Template; 6 import freemarker.template.TemplateModelException; 7 import freemarker.template.TemplateSequenceModel;
简单的代码的例子:
1 @Resource 2 private FreeMarkerConfigurer freemarkerConfigurer; 3 4 @Resource 5 private ServletContext servletContext; 6 7 public String getPraseHtmlFormTemplate(String templateString,Map<String, Object> paramMap, boolean readOnly, 8 IInitCallback initCallback,boolean preview) { 9 return praseHtmlFormTemplate(templateString, paramMap, readOnly, initCallback,preview); 10 } 11 12 protected String praseHtmlFormTemplate(String templateString, 13 Map<String, Object> paramMap, boolean readOnly,IInitCallback initCallback,boolean preview) { 14 Configuration cfg =freemarkerConfigurer.getConfiguration(); 15 cfg.setCustomAttribute("initCallback", initCallback); 16 cfg.setCustomAttribute("readOnly", readOnly); 17 cfg.setCustomAttribute("preview", preview); 18 cfg.setTemplateLoader(new StringTemplateLoader(templateString)); 19 Template template; 20 try { 21 template = cfg.getTemplate(""); 22 StringWriter writer = new StringWriter(); 23 Environment env = template.createProcessingEnvironment(paramMap, writer); 24 env.setCustomAttribute("paramMap", paramMap); 25 env.process(); 26 return writer.toString(); 27 } catch (Exception e) { 28 logger.error("解析模板文件错误:" + e.getMessage()); 29 e.printStackTrace(); 30 } 31 return ""; 32 }