FreeMarker 是一款模板引擎: 即一種基于模板和要改變的數(shù)據(jù), 并用來生
成輸出文本(HTML 網(wǎng)頁、電子郵件羊初、配置文件、源代碼等)的通用工具什湘。 它不
是面向最終用戶的长赞,而是一個(gè) Java 類庫,是一款程序員可以嵌入他們所開發(fā)產(chǎn)
品的組件闽撤。
FTL代表FreeMarker模板語言
public void test() throws Exception {
// 創(chuàng)建配置對(duì)象
Configuration configuration = new Configuration(Configuration.getVersion());
// 設(shè)置默認(rèn)生成文件編碼
configuration.setDefaultEncoding("utf-8");
// 設(shè)置模板路徑
configuration.setClassForTemplateLoading(FreemarkerTest.class, "/ftl");
// 獲取模板
Template template = configuration.getTemplate("test.ftl");
// 加載數(shù)據(jù)
Map<String, Object> dataModel = new HashMap<>();
dataModel.put("name", "傳智播客");
dataModel.put("message", "歡迎使用 Freemarker涧卵。");
// 創(chuàng)建輸出對(duì)象
FileWriter fileWriter = new FileWriter("D:\\itcast\\test\\test.html");
// 渲染模板和數(shù)據(jù)
template.process(dataModel, fileWriter);
// 關(guān)閉輸出
fileWriter.close();
}
一些常見的符號(hào)說明:
${ }插值;只能輸出數(shù)值腹尖、日期或者字符串柳恐,其它類型不能輸出伐脖。
<#freemarker 命令
<#-- 注釋 -->
<@使用自定義命令
??是判斷對(duì)象是否存在
?函數(shù)調(diào)用
<#assign name=value> 此指令用于在頁面上定義一個(gè)變量。
<#include path> path 參數(shù)可以是如 "foo.ftl" 和 "../foo.ftl" 一樣的相對(duì)路徑乐设,或者是如
"/foo.ftl" 這樣的絕對(duì)路徑
導(dǎo)入依賴
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
springmvc.xml整合freemarker
<!--整合freemarker-->
<bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="defaultEncoding" value="utf-8"/>
<!--模板路徑-->
<property name="templateLoaderPath" value="/views"/>
</bean>
<!--配置freemarker視圖解析器-->
<bean id="freeMarkerViewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="suffix" value="ftl"/>
<property name="contentType" value="text/html;charset=utf-8"/>
</bean>
<!--靜態(tài)頁面存放地址ITEM_HTML_PATH-->
<context:property-placeholder location="classpath:properties/page.properties"/>
導(dǎo)入ftl模板
web層用ModelAndView 接受發(fā)送信息