FreeMarker快速上手
創建Configuration實例
首先必須創建一個freemarker.template.Configuration 實例并調整其設置。Configuration 實例保存freemarker的設置,同時處理預解析的模板的創建和緩存。
通常應用程序的生命周期中只會創建一個Configuration實例。
Configuration cfg = new Configuration(); // 指定模板文件的數據源,這里是一個文件目錄。cfg.setDirectoryForTemplateLoading(new File("/where/you/store/templates")); // 指定模板如何發現數據模型,這是一個高級主題,暫且這樣使用。 cfg.setObjectWrapper(new DefaultObjectWrapper());?
目前我們使用單個的Configuration實例。不過如果一個系統有多個獨立的組件使用FreeMarker,它們會使用各自的Configuration 實例。?
創建數據模型
我們可以簡單地使用java.lang java.util 和自定義的JavaBean構建對象模型,比如我們構建數據模型如下:?
?
(root)|+- user = "Big Joe"|+- latestProduct|+- url = "products/greenmouse.html"|+- name = "green mouse"?
如下是構建數據模型的代碼:
// Create the root hash Map root = new HashMap(); // Put string ``user'' into the root root.put("user", "Big Joe"); // Create the hash for ``latestProduct'' Map latest = new HashMap(); // and put it into the root root.put("latestProduct", latest); // put ``url'' and ``name'' into latest latest.put("url", "products/greenmouse.html"); latest.put("name", "green mouse");?
也可以使用一個包含url 和 name 屬性的JavaBean實例表示lastestProduct。
獲取模板
模板通過freemarker.template.Template實例表示。通常從Configuration 實例中獲取Template實例,任何時候都可以調用getTemplate方法獲取一個Template 實例。假定模板文件test.ftl 保存在先前設置的目錄中:
Template temp = cfg.getTemplate("test.ftl");?
上述代碼將讀取,解析/where/you/store/templates/test.ftl文件,創建一個對應的Template實例 。
Configuration 緩存Template 實例, 因此當需要再次獲取test.ftl 文件, 將不會創建一個新的Template實例。
合并模板和數據模型
就我們所知,數據模型+模板=輸出,通過調用模板的process 方法合并數據模型和模板,process. 方法接受一個數據模型根和一個writer作為參數,將結果輸出到Writer。 為簡化起見,這里輸出到控制臺。
Writer out = new OutputStreamWriter(System.out); temp.process(root, out); out.flush();?
一旦獲取一個Template 實例,可以合并不同的數據模型和一個模板(Template 實例基本上是無狀態的),而test.ftl只會當Template 實例被創建的時候訪問一次。
?
當然這里的out可以為文件,可以是XML、java等你想要的任何文件類型,這樣就實現在代碼的生成.
整合
這是先前代碼片斷的源文件,不要忘記將freemarker.jar放在CLASSPATH.中。
import freemarker.template.*; import java.util.*; import java.io.*;public class Test {public static void main(String[] args) throws Exception {/* ------------------------------------------------------------------- */ /* You usually do it only once in the whole application life-cycle: */ /* Create and adjust the configuration */Configuration cfg = new Configuration();cfg.setDirectoryForTemplateLoading(new File("/where/you/store/templates"));cfg.setObjectWrapper(new DefaultObjectWrapper());/* ------------------------------------------------------------------- */ /* You usually do these for many times in the application life-cycle: */ /* Get or create a template */Template temp = cfg.getTemplate("test.ftl");/* Create a data model */Map root = new HashMap();root.put("user", "Big Joe");Map latest = new HashMap();root.put("latestProduct", latest);latest.put("url", "products/greenmouse.html");latest.put("name", "green mouse");/* Merge data model with template */Writer out = new OutputStreamWriter(System.out);temp.process(root, out);out.flush();} }?
總結
以上是生活随笔為你收集整理的FreeMarker快速上手的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: FreeMarker Eclipse P
- 下一篇: ldap的shema