1.jar包:freemarker-2.3.19.jar,將jar拷貝到lib目錄下;html
2.新建Web項目:TestFreeMarkerjava
在web目錄下新建ftl文件夾;web
在ftl下新建模版文件ftl03.ftl測試
<#ftl attributes={"content_type":"text/html; charset=UTF-8"}> <?xml version="1.0" encoding="utf-8"?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> ${hello},cfg.setDirectoryForTemplateLoading(new File("/ftl"));測試 </body> </html>
3.Java測試類FreeMarkerDemo:ui
package com.freemarker.test; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import freemarker.template.Configuration; import freemarker.template.Template; public class FreeMarkerDemo { public static void main(String[] args) { try { // 經過Freemaker的Configuration讀取相應的ftl Configuration cfg = new Configuration(); // 設定去哪裏讀取相應的ftl模板文件 cfg.setDirectoryForTemplateLoading(new File("D:/workspace/TestFreeMarker/WebContent/ftl")); // 在模板文件目錄中找到名稱爲name的模板文件 Template template = cfg.getTemplate("ftl03.ftl"); Map<String, Object> root = new HashMap<String, Object>(); root.put("hello", "Hello FreeMarker!"); root.put("files", "li"); //以字符串形式在控制檯輸出 StringWriter stringWriter = new StringWriter(); template.process(root, stringWriter); String resultStr = stringWriter.toString(); System.out.println(resultStr); //以文件形式輸出到指定文件 PrintWriter pt = new PrintWriter(new File("D:/pt.txt")); template.process(root, pt); } catch (Exception e) { e.printStackTrace(); } } }
控制檯輸出結果resultStr:spa
<?xml version="1.0" encoding="utf-8"?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> Hello FreeMarker!,cfg.setDirectoryForTemplateLoading(new File("/ftl"));測試 </body> </html>
同時在D盤生成pt.txt文件,內容與resultStr相同。code