<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version> </dependency>
----------產品詳細----------
產品名稱:${name}
產品價格:${price}
設計作者:<#list users as user> ${user} #list>
------------------------------
Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
cfg.setDirectoryForTemplateLoading(new File("src/main/java/templates"));
cfg.setDefaultEncoding("UTF-8");
Map data = new HashMap<>();
data.put("name", "Huwei P8");
data.put("price", "3985.7");
data.put("users", new String[]{"Tom","Jack","Rose"});
Template temp = cfg.getTemplate("product.ftl");
Writer out = new OutputStreamWriter(System.out);
temp.process(data, out); // 輸出到控制台
Article、服務類 ArticleService(模擬數據)newsList.ftl(列表)、news.ftl(詳情)News:檢查靜態文件是否存在 → 不存在則渲染生成列表頁與詳情頁 → 轉發 index.htmlweb.xml 設置 index.html 為首頁,index.jsp 轉發到 Servlet生成目錄結構:
webapp/
index.html // 新聞列表
news/
20160701.html // 單篇新聞
20160702.html
...
<#-- ... --> 不輸出${...} 或 #{...} 輸出變量<#directive> 控制邏輯<#if>/<#elseif>/<#else> 條件判斷<#list items as item> 迭代,內置 item_index、item_has_next<#include "file.ftl"> 包含模板<#macro name param> 定義宏(復用片段),<@name param=value> 調用<#assign var=value> 定義變量<#setting name=value> 設置環境(locale、number_format 等)<#escape x as x?html> 批量轉義輸出[1,2,3]、Map {"k":"v"}user.name、list[0]、map.key${"Hello ${user}"} 或 "Hello " + user?html、?upper_case、?size、?intvar!default、var??GitHub 項目地址:github下載或預覽代碼