java中jsp Freemarker詳解
Freemarker是一款模板引擎,是一種基於模版生成靜態檔案的通用工具,它是使用純java編寫的,一般用來生成HTML頁面。
原理 Freemarker 生成靜態頁面,首先需要使用自己定義的模板頁面,這個模板頁面可以是最最普通的html,也可以是巢狀freemarker中的 取值表示式, 標籤或者自定義標籤等等,然後後臺讀取這個模板頁面,解析其中的標籤完成相對應的操作, 然後採用鍵值對的方式傳遞引數替換模板中的的取值表示式,做完之後 根據配置的路徑生成一個新的html頁面, 以達到靜態化訪問的目的。
FreeMarker模板檔案
- 文字,直接輸出的部分
- 註釋,即<#–…-->格式不會輸出
- 插值(Interpolation):即${…}或者#{…}格式的部分,將使用資料模型中的部分替代輸出
- FTL指令:FreeMarker指令,和HTML標記類似,名字前加#予以區分,不會輸出。
<html> <body> <#-- 註釋部分 --> <br> <#-- 下面使用插值 --> <h1>Welcome ${user} !</h1> <p>We have these animals: <u1> <#-- 使用FTL指令 --> <#list animals as being> <li>${being.name} </li> <#list> <u1> </body> </html>
指令 list
<#list nameList as names>
${names}
</#list>
主要是進行迭代伺服器端傳遞過來的List集合,name是list迴圈的時候取的一個迴圈變數.相關指令
item_index:當前變數的索引值 item_has_next:是否存在下一個物件 break:跳出迭代
if指令
<#if (names=="javaschool")>
請訪問:www.51gjie.com
</#if>
該標籤主要是做if判斷用的,要注意的是條件等式必須用括號括起來。
include
<#include filename> <#include filename options>
該標籤用於匯入檔案。option包含下面2種屬性:
encoding=”GBK” 編碼格式 parse=true 是否作為ftl語法解析,預設是true,false就是以文字方式引入.注意在ftl檔案里布爾值都是直接賦值的如parse=true,而不是parse=”true”
<#include "include.html"/>
<#include "/common/copyright.ftl" encoding=”GBK”>
switch , case , default , break指令
<#switch value>
<#case refValue>...<#break>
<#case refValue>...<#break>
<#default>...
</#switch>
import指令
<#import path as hash>
noparse指令
<#noparse>...</#noparse>
noparse指令指定FreeMarker不處理該指定裡包含的內容。
<#noparse>
<#list books as book>
<tr><td>${book.name}<td>作者:${book.author}
</#list>
</#noparse>
escape,noescape指令
<#escape identifier as expression>...
<#noescape>...</#noescape>
</#escape>
escape指令導致body區的插值都會被自動加上escape表示式,但不會影響字串內的插值,只會影響到body內出現的插值。
assign指令
<#assign name=value> or <#assign name1=value1 name2=value2 ... nameN=valueN>
<#assign same as above... in namespacehash>
<#assign name>
capture this
</#assign>
<#assign name in namespacehash>
capture this
</#assign>
assign指令用於為該模板頁面建立或替換一個頂層變數。
setting指令
<#setting name=value>
該指令用於設定FreeMarker的執行環境,name的取值範圍包含如下幾個:
locale:該選項指定該模板所用的國家/語言選項
number_format:指定格式化輸出數字的格式
boolean_format:指定兩個布林值的語法格式,預設值是true,false
date_format,time_format,datetime_format:指定格式化輸出日期的格式
time_zone:設定格式化輸出日期時所使用的時區
搭建Freemarker環境 1. 使用maven來構建,pom.xml下載jar包
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.wxp.freemarker</groupId>
<artifactId>freemarker01</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>freemarker01</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<!-- Freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.20</version>
</dependency>
</dependencies>
</project>
2. 建立Freemarker根據資料和模型生成Html頁面的工具類FreemarkerUtil
package test.freemarker;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class FreemarkerUtil {
public Template getTemplate(String name) {
Template temp = null;
try {
// 通過Freemarker的Configuration讀取相應的Ftl
Configuration cfg = new Configuration();
// 設定去哪裡讀取相應的ftl模板
cfg.setClassForTemplateLoading(this.getClass(), "/ftl");
// 在模板檔案目錄中尋找名稱為name的模板檔案
temp = cfg.getTemplate(name);
} catch (IOException e) {
e.printStackTrace();
}
return temp;
}
/**
* 控制檯輸出檔案內容
* @param name
* @param rootMap
*/
public void print(String name, Map<String, Object> rootMap) {
try {
// 通過Template類可以將模板檔案輸出到相應的檔案
Template temp = this.getTemplate(name);
temp.process(rootMap, new PrintWriter(System.out));
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 將替換後的模板內容輸出到檔案
* @param name
* @param rootMap
* @param outFile
*/
public void fprint(String name, Map<String, Object> rootMap, String outFile) {
FileWriter out = null;
try {
out = new FileWriter(new File("D:\\freemarker\\ftl\\html\\"
+ outFile));
Template template = this.getTemplate(name);
template.process(rootMap, out);
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != out)
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3. 來建立Freemarker的模板ftl檔案
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
你好,${username}
</body>
</html>
4. 測試生成html頁面
package test.freemarker;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.wxp.freemarker.model.User;
public class TestFreemarker {
private FreemarkerUtil freemarkerUtil;
private Map<String, Object> rootMap = null;
@Before
public void setUp() {
freemarkerUtil = new FreemarkerUtil();
rootMap = new HashMap<String, Object>();
}
@Test
public void test01() {
// 填充資料
rootMap.put("username", "51gjie");
// 列印到控制檯
freemarkerUtil.print("01.ftl", rootMap);
// 輸出到檔案
freemarkerUtil.fprint("01.ftl", rootMap, "01.html");
}
}
執行結果生成html頁面
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
你好,51gjie
</body>
</html>
總結
-
FreeMarker是一款模板引擎:即一種基於模板、用來生成輸出文字(任何來自於 HTML格式的文字用來自動生成原始碼)的通用工具。它是為 Java 程式設計師提供的一個開發包,或者說是一個類庫。
-
FreeMarker 不是 Web 開發的應用程式框架。它是一個適用於Web應用程式框架中的元件,但是FreeMarker引擎本身並不知道 HTTP協議或 Java Servlet 的存在。它僅僅來生成文字內容。