Freemarker 模板引擎

目錄

  • 概念
  • 經常使用類型及條件
  • 實踐
  • 三種獲取內置模板
  • 獲取外部模板

content:

1. 概念

是一款模板引擎,用來將html和後端數據結合在一塊兒使用的通用類庫。實際上是一個java類庫。html

html模板 + 後端數據 = 輸出java

2. 經常使用類型及條件

經常使用類型:git

  1. 值:${key}表示
  2. 對象:${object.屬性}
1. if else
<#if condition>
...
<#elseif condition2> 
...
<#else>
...
</#if>  <!--必定要加的-->
...
複製代碼
2. gt/gte
<#if x == 0>
...
<!-- 用gt表明大於 -->
<#elseif x gt 0 >
...
<!-- 用gte 表明小於 -->
<#elseif x gte 0>
...
複製代碼
3. list
<!-- 判斷數組是否等空 -->
<#if list?? && (list?size > 0)>
...
</#if>
<!-- 循環數組 -->
 <#list categoryList as categorys>
複製代碼

3. 實踐

建立Configuration實例 + 數據模板(Map)+ 獲取模板 + 合併github

try {
    //1. 建立一個合適的Configration對象
    Configuration cfg = new Configuration(); 
    cfg.setDefaultEncoding("UTF-8");  //必須 
    // 2. 數據模板
    Map<String, Object> paramMap = new HashMap<>();
    paramMap.put("list", categoryList);
    paramMap.put("date", LocalDateTime.now().toLocalDate());
    // 獲取模板 
    ....
    // 合併,不須要輸出時,注掉
    //Writer writer = new OutputStreamWriter(new FileOutputStream("success.ftl"), "UTF-8");
    //template.process(paramMap, writer);
    // 將html輸出
    String htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, paramMap);
} catch (TemplateException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
複製代碼

模板加載器的方式:web

  1. 內建模板加載器 ok
  2. 從多個位置加載
  3. 從其餘資源加載 ok
  4. 模板路徑

4. 三種內建模板加載器

1. setDirectoryForTemplateLoading(File dir) 利用本地路徑加載模板

本地模板路徑:src/main/webapp/WEB-INF/template/model.ftlspring

// 把磁盤的路徑來擼下來,若是要上測試,線上環境就不兼容了
configuration.setDirectoryForTemplateLoading(new File(
C:\Users\xxx\Desktop\project\src\main\webapp\WEB-INF\template));
Template template = configuration.getTemplate("model.ftl");
複製代碼
2. setClassForTemplateLoading(Class cl, String prefix) 類加載機制
  1. 是經過類加載機制來加載模板的方式。
  2. 傳入的class參數會被 Class.getResource() 用來調用方法來找到模板。
  3. 參數 prefix 是加前綴的。
  4. 從類路徑下加載文件的這種機制,要比從文件系統的特定目錄位置加載安全並且簡單。

本地模板路徑:src\main\resources\template\model.ftl this.class 路徑:src\main\java\com\xxx\xxx\xxx\xxx\util\Util.java後端

configuration.setClassForTemplateLoading(this.getClass(), "/template");
Template template = configuration.getTemplate("model.ftl");
複製代碼
3. setServletContextForTemplateLoading(Object servletContext, String path) 應用上下文和基路徑 (若是不在webapp下是沒法加載的)

基路徑:Web應用根路徑(WEB-INF目錄的上級目錄)的相對路徑 加載應用上下文數組

// 1. 依賴注入serverContext
@AutoWried
ServerContext serverContext;

// 2. 利用webApplication
WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
ServletContext context = webApplicationContext.getServletContext();
複製代碼

本地模板路徑:src/main/webapp/WEB-INF/template/model.ftl安全

//默認的路徑就在WEB-INF
configuration.setClassForTemplateLoading(serverContext, "/template");
Template template = configuration.getTemplate("model.ftl");
複製代碼

5. 從其餘資源加載:

1. 須要本身寫類加載器來繼承URLTemplateLoader

RemoteTemplateLoader.javaapp

public class RemoteTemplateLoader extends URLTemplateLoader {
    // 遠程模板文件的存儲路徑(目錄)
    private String remotePath;
    private static String yanxuanMailTemplate = "http://";

    public RemoteTemplateLoader(String remotePath) {
        if (remotePath == null) {
            throw new IllegalArgumentException("remotePath is null");
        }
        this.remotePath = canonicalizePrefix(remotePath);
        if (this.remotePath.indexOf('/') == 0) {
            this.remotePath = this.remotePath.substring(this.remotePath.indexOf('/') + 1);
        }
    }

    @Override
    protected URL getURL(String name) {
        name = name.replace("_zh_CN", "");  //不知道爲啥生成的總會有這個,因此replace掉了
        String fullPath = this.remotePath + name;
        System.out.println(fullPath);
        if ((this.remotePath.equals("/")) && (!isSchemeless(fullPath))) {
            return null;
        }
        URL url = null;
        try {
            url = new URL(fullPath);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return url;
    }

    private static boolean isSchemeless(String fullPath) {
        int i = 0;
        int ln = fullPath.length();

        if ((i < ln) && (fullPath.charAt(i) == '/')) {
            i++;
        }

        while (i < ln) {
            char c = fullPath.charAt(i);
            if (c == '/') {
                return true;
            }
            if (c == ':') {
                return false;
            }
            i++;
        }
        return true;
    }
}
複製代碼
2. 獲取模板 setTemplateLoader() 獲取外部路徑
//建立Configration對象
Configuration cfg = new Configuration();

//建立一個獲取外部url的
RemoteTemplateLoader remoteTemplateLoader = new RemoteTemplateLoader(yanxuanMailTemplate);
cfg.setTemplateLoader(remoteTemplateLoader);

Template template = cfg.getTemplate("/model.ftl");
複製代碼

利用freemarker模板發送郵件:https://github.com/yangshuting1/spring-send-mail

相關文章
相關標籤/搜索