FreeMarker開發-入門,freemarker開發入門
1. 下載freemarker.jar
可到官網下載:http://freemarker.org/。
下載的freemarker-2.3.23.tar.gz 3.2 MB 包含了freemarker.jar、源碼和API文檔。
2. 建立Java Project
1) 在項目中建立lib目錄,將freemarker.jar放入lib目錄,並“Add to build path”。
2) 在src下建立templates目錄,用於存放模板檔案。在templates目錄下建立example.flt檔案,內容如下:
${example}
3) 在src下建立測試類別FreeMarkerTest。內容如下:
1 public class FreeMarkerTest { 2 public static void main(String[] args) throws IOException, 3 TemplateException { 4 Configuration conf = new Configuration(); 5 // 設定載入模板檔案的目錄 6 conf.setDirectoryForTemplateLoading(new File("src/templates")); 7 // 設定模板檢索資料模型的方式 8 conf.setObjectWrapper(new DefaultObjectWrapper()); 9 // 建立、解析模板並緩衝10 Template template = conf.getTemplate("example.flt");11 // 準備資料12 Map<String, Object> root = new HashMap<String, Object>();13 root.put("example", "Hello World!");14 // 將資料與模板合并15 template.process(root, new OutputStreamWriter(System.out));16 }17 }
4) 運行FreeMarkerTest,輸出如下:
Hello World!
3. 關聯FreeMarker源碼到eclipse
從freemarker-2.3.23.tar.gz中解壓出source目錄,關聯到eclipse,方便在開發中查看源碼。