1. 程式人生 > >頁面靜態化技術:FreeMarker

頁面靜態化技術:FreeMarker

頁面靜態化技術:FreeMarker

背景: 為了實現頁面的管理和快速上線,需要用到頁面靜態化
如何: 頁面靜態化就是使用 模板+資料,通過技術手段將兩者合二為一,生成一個html頁面
業務流程:

  1. 獲取模型所需要的資料
  2. 製作模版
  3. 利用靜態化技術生成html
  4. 將html頁面存放在檔案系統中
  5. 從檔案系統中取出釋出到網頁上

學習freemarker

1.匯入freemarker的依賴

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

2.在resource目錄下建立配置檔案application.yml

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

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>

4.建立啟動類

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

5.建立模板資料類

@Data
@ToString
public class Student {
    private String name;//姓名
    private int age;//年齡
    private Date birthday;//生日
    private Float money;//錢包
    private List<Student> friends;//朋友列表 private Student bestFriend;//最好的朋友
}

6.建立controller

@Controller
@RequestMapping("/freemarker")
public class FreemarkerController {

    @RequestMapping("/test1")
    public String freemarker(Map<String,Object> map){
        map.put("name","奧特曼");
        return "test1";
    }
}

7.訪問工程,埠為8088

freemarker的基礎語法

1.註釋:<#–註釋–>
2.差值表示式:${name},從模板中取出資料的
3.ftl表示式,接下來要重點學習的
4.文字,就是不用任何表示式的純文字,直接展示在頁面上

建立模板

@Controller
@RequestMapping("/freemarker")
public class FreemarkerController {

    @RequestMapping("/test1")
    public String freemarker(Map<String,Object> map){
        map.put("name","奧特曼");
        //向資料模型放資料 map.put("name","黑馬程式設計師");
        Student stu1 = new Student();
        stu1.setName("小明");
        stu1.setAge(18);
        stu1.setMoney(1000.86f);
        stu1.setBirthday(new Date());
        Student stu2 = new Student();
        stu2.setName("小紅");
        stu2.setMoney(200.1f);
        stu2.setAge(19);
        stu2.setBirthday(new Date());
        List<Student> friends = new ArrayList<>();
        friends.add(stu1);
        //給學生2設定朋友列表
        stu2.setFriends(friends);
        //給學生2設定最好的朋友為學生1
        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";
    }
}

list表示式

<#list stus as stu>
<#--如果使用序號-->
<td>${stu_index}</td>
<td>${stu.name}</td>
…… ……
</list>

栗子

<body>
    Hello ${name}!
    <br/>
    使用list指令
    <br/>
    <table>
        <tr>
            <td>序號</td>
            <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>生日</td>
                <td>${stu.money}</td>
            </tr>
        </#list>

    </table>
</body>

Map表示式

獲取map列表中的資料
    1。通過[]來獲取資料<br/>
    姓名:${stuMap['stu1'].name}<br/>
    年齡:${stuMap['stu1'].age}<br/>
    <br/>
    2.通過點來獲取資料<br/>
    姓名:${stuMap.stu1.name}<br/>
    年齡:${stuMap.stu1.age}
    <br/>
    3.遍歷Map
    <table>
        <tr>
            <td>序號</td>
            <td>姓名</td>
            <td>年齡</td>
            <td>錢包</td>
        </tr>
        <#list stuMap?keys as key>
            <tr>
                <td>${key_index+1}</td>
                <td>${stuMap[key].name}</td>
                <td>${stuMap[key].age}</td>
                <td>${stuMap[key].money}</td>
            </tr>
        </#list>
    </table>

if表示式

如果年齡大於18歲背景顏色就為綠色

<#--注意中間的括號是要加上的-->
<td <#if (stuMap[key].age>18)> bgcolor="blue" </#if>>${stuMap[key].name}</td>
或者不加括號
<td <#if stuMap[key].age &gt 18> bgcolor="blue" </#if>>${stuMap[key].name}</td>

空值處理

1.判斷某個變數是否存在,使用"??"。栗子:list??,如果存在返回true,不存在返回false,一般用在集合或者是物件上面

<#if list??>
  ………………          
</#if>

2.缺失變數預設值使用 “!” 使用!要以指定一個預設值,當變數為空時顯示預設值。
例: ${name!’’}表示如果name為空顯示空字串。
如果是巢狀物件則建議使用()括起來。

年齡:${(stuMap.stu1.age)!''}

內建函式

內建函式語法格式: 變數+?+函式名稱
1.顯示某個集合的大小

size:${stus?size}

2.顯示日期

顯示年月日: ${today?date} 
顯示時分秒:${today?time} 
顯示日期+時間:${today?datetime}  
自定義格式化: ${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}