首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

FreeMarker 常用指令完整實戰指南

     編輯:Java 程式設計入門

開發環境

  • 框架:Spring MVC + FreeMarker
  • IDE:SpringSource Tool Suite 2.9.0
  • JDK:1.6.0_29
  • Tomcat:7.0.26

Controller 層準備資料

@Controller
public class HelloWorldController {
    @RequestMapping("/helloWorld")
    public String helloWorld(Model model) {
        // 1. 基本變數
        model.addAttribute("flag", 0);
        
        // 2. 空 List
        List noExistList = null;
        model.addAttribute("noExistList", noExistList);
        
        // 3. 一般 List
        List strList = Arrays.asList("www.", "cnblogs.", "com/sunang");
        model.addAttribute("strList", strList);
        
        // 4. Map
        Map strMap = new HashMap<>();
        strMap.put("mapKey0", "www.");
        strMap.put("mapKey1", "cnblogs.");
        strMap.put("mapKey2", "com/sunang");
        model.addAttribute("strMap", strMap);
        
        // 5. 日期物件
        model.addAttribute("nowTime", new Date());
        
        return "helloWorld.ftl";
    }
}

FTL 模板核心指令詳解

1. 條件判斷 <#if>

<#if flag == 1>
    flag = 1
<#elseif flag == 2>
    flag = 2
<#else>
    flag!=1 && flag!=2 flag的值為:${flag}
</#if>

重點: 指令內直接用變數名,指令外用 ${變數} 輸出。

2. 變數存在性檢查 ??

<#if noExistList??>
    List存在
<#else>
    List不存在
</#if>

防止 NullPointerException 的必備技巧。

3. 列表迭代 <#list>

<#list strList as sl>
    <#if sl_index == 0>
        我的博客地址是:${sl}
    <#else>
        ${sl}
    </#if>
</#list>
  • sl_index:索引(從 0 開始)
  • sl_has_next:是否有下一項
  • sl_is_first、sl_is_last:首尾判斷

4. 直接下標存取

${strList[0]}${strList[1]}${strList[2]}

5. Map 取值

${strMap.mapKey0}${strMap.mapKey1}${strMap.mapKey2}

6. 日期格式化

${nowTime?string("yyyy-MM-dd")}

常用格式:yyyy-MM-dd HH:mm:ss、yyyy/MM/dd 等。

執行驗證

部署至 Tomcat,瀏覽器訪問:https://localhost:8080/專案名/helloWorld.htm

執行結果截圖

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved