使用freemarker.jar
使用示例
1 package com.test; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.io.StringWriter; 6 import java.util.HashMap; 7 import java.util.Locale; 8 import java.util.Map; 9 10 import freemarker.template.Configuration; 11 import freemarker.template.DefaultObjectWrapper; 12 import freemarker.template.Template; 13 14 public class FreemarkerHandler { 15 16 protected static Configuration freemarkerConfig; 17 private static FreemarkerHandler instance = new FreemarkerHandler(); 18 19 public static void main(String[] args){ 20 Map<String, Object> root = new HashMap<String, Object>(); 21 root.put("user", "joe"); 22 root.put("sex", "男"); 23 FreemarkerHandler.getInstance("/where/your/store/templates").docXmlBulider(root, "text.ftl"); 24 } 25 26 /** 27 * @param rootPath 加载数据源的目录 28 */ 29 public static FreemarkerHandler getInstance(String rootPath) { 30 /** 31 * 创建和调整配置 32 * 在整个应用的生命周期中,此操作应该只做一次 33 */ 34 if (null == freemarkerConfig) { 35 freemarkerConfig = new Configuration(); 36 try { 37 freemarkerConfig.setDirectoryForTemplateLoading(new File(rootPath)); 38 freemarkerConfig.setObjectWrapper(new DefaultObjectWrapper()); 39 freemarkerConfig.setEncoding(Locale.CHINA, "utf-8"); 40 freemarkerConfig.setNumberFormat("#"); 41 } catch (IOException e) { 42 e.printStackTrace(); 43 } 44 } 45 return instance; 46 } 47 /** 48 * 49 * @param entity 数据存放对象 50 * @param ftlName 模板(路径+名称) 51 * @return 52 */ 53 public String docXmlBulider(Object entity, String ftlName) { 54 StringWriter writer = new StringWriter(); 55 String content = ""; 56 try { 57 /** 58 * 获取或创建模板 59 * 在整个应用的生命周期中,这个工作可以执行多次 60 */ 61 Template temp = freemarkerConfig.getTemplate(ftlName); 62 // 模板和数据类型合并 63 temp.process(entity, writer); 64 content = writer.toString(); 65 } catch (Exception e) { 66 e.printStackTrace(); 67 } 68 return content; 69 } 70 }