Freemarker初識與核心指令

1 FreeMarker 研究

1.1 FreeMarker 介紹

1、freemarker是一個用Java開發的模板引擎

在這裏插入圖片描述在這裏插入圖片描述常用的java模板引擎還有哪些?
Jsp、Freemarker、Thymeleaf 、Velocity 等。

2、模板+數據模型=輸出

freemarker並不關心數據的來源,只是根據模板的內容,將數據模型在模板中顯示並輸出文件(通常爲html,也可以生成其它格式的文本文件)
1、數據模型
數據模型在java中可以是基本類型也可以List、Map、Pojo等複雜類型。
2、來自官方的例子:(https://freemarker.apache.org/docs/dgui_quickstart_basics.html
數據模型:
在這裏插入圖片描述模板:
在這裏插入圖片描述輸出:
在這裏插入圖片描述

1.2 FreeMarker 快速入門

freemarker作爲springmvc一種視圖格式,默認情況下SpringMVC支持freemarker視圖格式。
需要創建Spring Boot+Freemarker工程用於測試模板。

1.2.1 創建測試工程

創建一個freemarker 的測試工程專門用於freemarker的功能測試與模板的測試。
pom.xml 如下

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <parent>
        <artifactId>xc-framework-parent</artifactId>
        <groupId>com.xuecheng</groupId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../xc-framework-parent/pom.xml</relativePath>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>test-freemarker</artifactId>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
        </dependency>
    </dependencies>
</project>

1.2.2 配置文件

配置application.yml和 logback-spring.xml,從cms工程拷貝這兩個文件,進行更改, logback-spring.xml無需更
改,application.yml內容如下:

server:
  port: 8088 #服務端口

spring:
  application:
    name: test-freemarker #指定服務名
  freemarker:
    cache: false  #關閉模板緩存,方便測試
    settings:
      template_update_delay: 0 #檢查模板更新延遲時間,設置爲0表示立即檢查,如果時間大於0會有緩存不方便進行模板測試


1.2.3 創建模型類

在freemarker的測試工程下創建模型類型用於測試
我自己使用的Lombok,你也可以使用getter,setter代替

package com.test.freemarker.model;

import lombok.Data;
import lombok.ToString;

import java.util.Date;
import java.util.List;

/**
 * @author Administrator
 * @version 1.0
 * @create 2018-06-13 8:24
 **/
@Data
@ToString
public class Student {
    private String name;//姓名
    private int age;//年齡
    private Date birthday;//生日
    private Float mondy;//錢包
    private List<Student> friends;//朋友列表
    private Student bestFriend;//最好的朋友
}

1.2.3 創建模板

在 src/main/resources下創建templates,此目錄爲freemarker的默認模板存放目錄。
在templates下創建模板文件test1.ftl,模板中的${name}最終會被freemarker替換成具體的數據。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Hello World!</title>
</head>
<body>
Hello ${name}!
</body>
</html>

1.2.4 創建controller

創建Controller類,向Map中添加name,最後返回模板文件。

package com.test.freemarker.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
@RequestMapping("/freemarker")
@Controller
public class FreemarkerController {
    @Autowired
    RestTemplate restTemplate;
    @RequestMapping("/test1")
    public String freemarker(Map<String, Object> map){
        map.put("name","馬冬梅");
        //返回模板文件名稱
        return "test1";
    }
}

1.2.5 創建啓動類

@SpringBootApplication
public class FreemarkerTestApplication {
    public static void main(String[] args) {
        SpringApplication.run(FreemarkerTestApplication.class,args);
    }
}

1.2.6 測試

請求:http://localhost:8088/freemarker/test1
屏幕顯示: Hello 馬冬梅!

1.3 FreeMarker 基礎

1.3.1 核心指令

1.3.1.1 數據模型

Freemarker靜態化依賴數據模型和模板,下邊定義數據模型:
下邊方法形參map即爲freemarker靜態化所需要的數據模型,在map中填充數據:

@RequestMapping("/test1")
    public String freemarker(Map<String, Object> map){
        //向數據模型放數據
        map.put("name","馬冬梅");
        Student stu1 = new Student();
        stu1.setName("小明");
        stu1.setAge(18);
        stu1.setMondy(1000.86f);
        stu1.setBirthday(new Date());
        Student stu2 = new Student();
        stu2.setName("小紅");
        stu2.setMondy(200.1f);
        stu2.setAge(19);
		// stu2.setBirthday(new Date());
        List<Student> friends = new ArrayList<>();
        friends.add(stu1);
        stu2.setFriends(friends);
        stu2.setBestFriend(stu1);
        List<Student> stus = new ArrayList<>();
        stus.add(stu1);
        stus.add(stu2);
        //向數據模型放數據
        map.put("stus",stus);
        //準備map數據
        HashMap<String,Student> stuMap = new HashMap<>();
        stuMap.put("stu1",stu1);
        stuMap.put("stu2",stu2);
        //向數據模型放數據
        map.put("stu1",stu1);
        //向數據模型放數據
        map.put("stuMap",stuMap);
        //返回模板文件名稱
        return "test1";
    }

1.3.1.2 List指令

本節定義freemarker模板,模板中使用freemarker的指令,關於freemarker的指令需要知道:

1、註釋,即<#‐‐和‐‐>,介於其之間的內容會被freemarker忽略
2、插值(Interpolation):即${..}部分,freemarker會用真實的值代替${..}
3、FTL指令:和HTML標記類似,名字前加#予以區分,Freemarker會解析標籤中的表達式或邏輯。
4、文本,僅文本信息,這些不是freemarker的註釋、插值、FTL指令的內容會被freemarker忽略解析,直接輸出內
容。

在test1.ftl模板中使用list指令遍歷數據模型中的數據:

<table>
    <tr>
     <td>序號</td>    
        <td>姓名</td>
        <td>年齡</td>
        <td>錢包</td>
    </tr>
    <#list stus as stu>
        <tr>
            <td>${stu_index + 1}</td>
            <td>${stu.name}</td>
            <td>${stu.age}</td>
            <td>${stu.mondy}</td>
        </tr>
    </#list>
</table>

3、輸出:
Hello 馬冬梅! 序號 姓名 年齡 錢包 1 小明 18 1,000.86 2 小紅 19 200.1

說明:
_index:得到循環的下標,使用方法是在stu後邊加"_index",它的值是從0開始

1.3.1.3 遍歷Map數據

1、數據模型
使用map指令遍歷數據模型中的stuMap。
2、模板

輸出stu1的學生信息:<br/>
姓名:${stuMap['stu1'].name}<br/>
年齡:${stuMap['stu1'].age}<br/>
輸出stu1的學生信息:<br/>
姓名:${stuMap.stu1.name}<br/>
年齡:${stuMap.stu1.age}<br/>
遍歷輸出兩個學生信息:<br/>
<table>
    <tr>
        <td>序號</td>
        <td>姓名</td>
        <td>年齡</td>
        <td>錢包</td>
    </tr>
<#list stuMap?keys as k>
<tr>
    <td>${k_index + 1}</td>
    <td>${stuMap[k].name}</td>
    <td>${stuMap[k].age}</td>
    <td >${stuMap[k].mondy}</td>
</tr>
</#list>
</table>

3 、輸出

輸出stu1的學生信息:
姓名:小明
年齡:18
輸出stu1的學生信息:
姓名:小明
年齡:18
遍歷輸出兩個學生信息:
序號 姓名 年齡 錢包        
1 小紅 19 200.1         
2 小明 18 1,000.86

1.3.1.4 if指令

if 指令即判斷指令,是常用的FTL指令,freemarker在解析時遇到if會進行判斷,條件爲真則輸出if中間的內容,否
則跳過內容不再輸出。
1、數據模型:
使用list指令中測試數據模型。
2、模板:

<table>
    <tr>
        <td>姓名</td>
        <td>年齡</td>
        <td>錢包</td>
    </tr>
     <#list stus as stu>
        <tr>
            <td <#if stu.name =='小明'>style="background:red;"</#if>>${stu.name}</td>
            <td>${stu.age}</td>
            <td >${stu.mondy}</td>
        </tr>
    </#list>
</table>

通過閱讀上邊的代碼,實現的功能是:如果姓名爲 “小明”則背景色顯示爲紅色。
3、輸出:
通過測試發現 姓名爲小明的背景色爲紅色。

1.3.2 其它指令

1.3.2.1 運算符

1、算數運算符 FreeMarker表達式中完全支持算術運算,FreeMarker支持的算術運算符包括:+, - , * , / , % 2、邏輯運算符 邏輯運算符有如下幾個: 邏輯與:&& 邏輯或:|| 邏輯非:! 邏輯運算符只能作用於布爾值,否則將產生錯誤 3、
比較運算符 表達式中支持的比較運算符有如下幾個: 1 =或者==:判斷兩個值是否相等. 2 !=:判斷兩個值是否不等. 3 >或者gt:判斷左邊值是否大於右邊值 4 >=或者gte:判斷左邊值是否大於等於右邊值 5 <或者lt:判斷左邊值是否小於右邊值 6 <=或者lte:判斷左邊值是否小於等於右邊值

注意: =和!=可以用於字符串,數值和日期來比較是否相等,但=和!=兩邊必須是相同類型的值,否則會產生錯誤,而且FreeMarker是精確比較,“x”,"x ","X"是不等的.其它的運行符可以作用於數字和日期,但不能作用於字符串,大部分的時
候,使用gt等字母運算符代替>會有更好的效果,因爲 FreeMarker會把>解釋成FTL標籤的結束字符,當然,也可以使用括號來避免這種情況,如:<#if (x>y)>

1.3.2.2 空值處理

1、判斷某變量是否存在使用 “??” 用法爲:variable??,如果該變量存在,返回true,否則返回false
例:爲防止stus爲空報錯可以加上判斷如下:

	<#if stus??>
	    <#list stus as stu>
	     ......    
	    </#list>
    </#if>

2、缺失變量默認值使用 “!” 使用!要以指定一個默認值,當變量爲空時顯示默認值。
例: ${name!’’}表示如果name爲空顯示空字符串。
如果是嵌套對象則建議使用()括起來。

例: ${(stu.bestFriend.name)!’’}表示,如果stu或bestFriend或name爲空默認顯示空字符串。

1.3.2.3 內建函數

內建函數語法格式: 變量+?+函數名稱

1、和到某個集合的大小
${集合名?size}
2、日期格式化
顯示年月日: ${today?date}
顯示時分秒:${today?time}  
顯示日期+時間:${today?datetime} <br>       
自定義格式化:  ${today?string("yyyy年MM月")}
3、內建函數c

map.put(“point”, 102920122);
point是數字型,使用${point}會顯示這個數字的值,不併每三位使用逗號分隔。

如果不想顯示爲每三位分隔的數字,可以使用c函數將數字型轉成字符串輸出

${point?c}

4、將json字符串轉成對象

一個例子:
其中用到了 assign標籤,assign的作用是定義一個變量。

<#assign text="{'bank':'工商銀行','account':'10101920201920212'}" />
<#assign data=text?eval />
開戶行:${data.bank}  賬號:${data.account}

1.3.2.4 完整的模板

上邊測試的模板內容如下,可自行進行對照測試。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Hello World!</title>
</head>
<body>
Hello ${name}!
<br/>
<table>
    <tr>
        <td>序號</td>
        <td>姓名</td>
        <td>年齡</td>
        <td>錢包</td>
    </tr>
    <#list stus as stu>
        <tr>
            <td>${stu_index + 1}</td>
            <td <#if stu.name =='小明'>style="background:red;"</#if>>${stu.name}</td>
            <td>${stu.age}</td>
            <td >${stu.mondy}</td>
        </tr>
    </#list>

</table>
<br/><br/>
輸出stu1的學生信息:<br/>
姓名:${stuMap['stu1'].name}<br/>
年齡:${stuMap['stu1'].age}<br/>
輸出stu1的學生信息:<br/>
姓名:${stu1.name}<br/>
年齡:${stu1.age}<br/>
遍歷輸出兩個學生信息:<br/>
<table>
    <tr>
        <td>序號</td>
        <td>姓名</td>
        <td>年齡</td>
        <td>錢包</td>
    </tr>
<#list stuMap?keys as k>
<tr>
    <td>${k_index + 1}</td>
    <td>${stuMap[k].name}</td>
    <td>${stuMap[k].age}</td>
    <td >${stuMap[k].mondy}</td>
</tr>
</#list>
</table>
</br>
<table>
    <tr>
        <td>姓名</td>
        <td>年齡</td>
        <td>出生日期</td>
        <td>錢包</td>
        <td>最好的朋友</td>
        <td>朋友個數</td>
        <td>朋友列表</td>
    </tr>
    <#if stus??>
    <#list stus as stu>
        <tr>
            <td>${stu.name!''}</td>
            <td>${stu.age}</td>
            <td>${(stu.birthday?date)!''}</td>
            <td>${stu.mondy}</td>
            <td>${(stu.bestFriend.name)!''}</td>
            <td>${(stu.friends?size)!0}</td>
            <td>
                <#if stu.friends??>
                <#list stu.friends as firend>
                    ${firend.name!''}<br/>
                </#list>
                </#if>
            </td>
        </tr>
    </#list>
    </#if>

</table>
<br/>
<#assign text="{'bank':'工商銀行','account':'10101920201920212'}" />
<#assign data=text?eval />
開戶行:${data.bank}  賬號:${data.account}

</body>
</html>

基礎打牢,勤加練習,下期我們介紹如何使用Freemarker導出word文檔?
如何在真實項目中導出個人簡歷保存到本地與輸出到瀏覽器?

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章