這裏有個系列博客很不錯,應該是最合適的入門教程了。Java模板引擎FreeMarker系列
這裏的對FreeMarker的簡介也很棒:使用Java對FreeMarker開發Web模板html
FreeMarker是一個模板引擎,一個基於模板生成文本輸出的通用工具,使用純Java編寫,被主要用來生成HTML頁面,特別是基於MVC模式的Web應用的頁面。固然,FreeMarker一樣能夠應用於非Web應用程序環境。雖然FreeMarker具備一些編程的能力,但一般由Java程序準備要顯示的數據,由FreeMarker模板顯示準備的數據(以下圖)java
FreeMarker不是一個Web應用框架,也與容器無關,由於它並不知道HTTP或者Servlet。它適合做爲Model2框架(如Struts)的視圖組件。FreeMarker模板也支持JSP標籤庫。編程
Freemarker生成靜態頁面的過程是,模板引擎讀取模板頁面,解析其中的標籤,完成指令相對應的操做,而後採用鍵值對的方式傳遞參數替換模板中的取值表達式,最後根據配置的路徑生成一個新的靜態頁面。app
${…}
:取值標籤。表示輸出變量的內容。如:${name}
能夠取得root中key爲name的值。${person.name}
能夠取得成員變量爲person的name屬性。框架
<#…>
:FTL指令(FreeMarker模板語言標記)如:<#if>
表示判斷、<#list>
表示循環枚舉、<#include>
表示包含其餘頁面。函數
<@…>
:宏,自定義標籤。工具
註釋:包含在<#--
和-->
之間。學習
模板 + 數據模型 = 輸出ui
英文就是 template + data-model = outputthis
首先,建立模板以下:
<html> <head> <title>Welcome!</title> </head> <body> <h1>Welcome ${user}!</h1> <p>Our latest product: <a href="${latestProduct.url}">${latestProduct.name}</a>! </body> </html>
在程序端,只須要簡單的四步:
獲得Configuration類的實例。
建立data-model對象。
獲取template文件。
把template和data-model捏合到一塊兒產生輸出。
代碼以下:
首先建立data-model類:
/** * Product bean; note that it must be a public class! */ public class Product { private String url; private String name; // As per the JavaBeans spec., this defines the "url" bean property // It must be public! public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } // As per the JavaBean spec., this defines the "name" bean property // It must be public! public String getName() { return name; } public void setName(String name) { this.name = name; } }
主函數:
import freemarker.template.*; import java.util.*; import java.io.*; public class Test { public static void main(String[] args) throws Exception { /* ------------------------------------------------------------------------ */ /* You should do this ONLY ONCE in the whole application life-cycle: */ /* Create and adjust the configuration singleton */ Configuration cfg = new Configuration(Configuration.VERSION_2_3_25); cfg.setDirectoryForTemplateLoading(new File("/where/you/store/templates")); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); cfg.setLogTemplateExceptions(false); /* ------------------------------------------------------------------------ */ /* You usually do these for MULTIPLE TIMES in the application life-cycle: */ /* Create a data-model */ Map root = new HashMap(); root.put("user", "Big Joe"); Product latest = new Product(); latest.setUrl("products/greenmouse.html"); latest.setName("green mouse"); root.put("latestProduct", latest); /* Get the template (uses cache internally) */ Template temp = cfg.getTemplate("test.ftlh"); /* Merge data-model with template */ Writer out = new OutputStreamWriter(System.out); temp.process(root, out); // Note: Depending on what `out` is, you may need to call `out.close()`. // This is usually the case for file output, but not for servlet output. } }
能夠看到,有了JSP的知識,FreeMarker仍是很好學習的。更多的用法能夠參考上面的博客以及官方教程。本篇到此爲止。