本文是一个很简单很基础的Freemarker模板解析测试类,复杂的也是在此基础上添加一些代码优化而来,懂得基础流程后就能融会贯通了
POM:
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.9</version> </dependency>
JAVA:
1 import java.io.File; 2 import java.io.FileReader; 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import java.io.Reader; 6 import java.io.Writer; 7 import java.util.Arrays; 8 import java.util.HashMap; 9 import java.util.Map; 10 11 import freemarker.template.Template; 12 import freemarker.template.TemplateException; 13 14 /** 15 * Freemarker测试类 16 * 17 * @author yzl 18 * @see [相关类/方法](可选) 19 * @since [产品/模块版本] (可选) 20 */ 21 public class FreemarkerTest { 22 public static void main(String[] args) throws IOException, TemplateException { 23 Reader reader = new FileReader(new File("E:/test.ftl")); 24 Template template = new Template("test", reader, null, "utf-8"); 25 26 Map<Object, Object> data = new HashMap<Object, Object>(); 27 data.put("userName", "hello world"); 28 data.put("list", Arrays.asList("entity1","entity2")); 29 Writer writer = new PrintWriter(System.out); 30 31 template.process(data, writer); 32 33 writer.flush(); 34 writer.close(); 35 reader.close(); 36 } 37 }
Ftl文件:
<p>姓名:${userName}</p> <p>List: <#list list as entity> ${entity}</br> </#list> </p>
输出结果:
<p>姓名:hello world</p> <p>List: entity1</br> entity2</br> </p>
原文:http://www.cnblogs.com/yangzhilong/p/6097211.html