本文是一個很簡單很基礎的Freemarker模板解析測試類,複雜的也是在此基礎上添加一些代碼優化而來,懂得基礎流程後就能融會貫通了java
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文件:spa
<p>姓名:${userName}</p> <p>List: <#list list as entity> ${entity}</br> </#list> </p>
輸出結果:code
<p>姓名:hello world</p> <p>List: entity1</br> entity2</br> </p>
解析Freemark字符串和ftl文件到字符串:blog
package com.longge.util; import java.io.File; import java.io.FileReader; import java.io.Reader; import java.io.StringWriter; import java.util.Map; import freemarker.template.Template; import lombok.NonNull; /** * @author roger yang * @date 7/04/2019 */ public class TemplateUtils { /** * parsing string * @param toParseStr * @param data * @return * @throws Exception */ public static String parsingString(@NonNull String toParseStr, @NonNull Map<String, Object> data) throws Exception { try(StringWriter sw = new StringWriter();) { Template template = new Template(toParseStr, toParseStr, null); template.process(data, sw); sw.flush(); return sw.toString(); } } /** * parsing with ftl file * @param file * @param data * @return * @throws Exception */ public static String parsingFtlFile(@NonNull File file, @NonNull Map<String, Object> data) throws Exception { try(Reader reader = new FileReader(file); StringWriter sw = new StringWriter();) { Template template = new Template(file.getName(), reader, null); template.process(data, sw); sw.flush(); return sw.toString(); } } /** * parsing with ftl file * @param file * @param data * @return * @throws Exception */ public static String parsingFtlFile(@NonNull String filePath, @NonNull Map<String, Object> data) throws Exception { File file = new File(filePath); return parsingFtlFile(file, data); } }