freemarker在SpringBoot下的使用以及出現的問題

可能真的因爲本人足夠菜…在這裏踩了好大的坑…所以爲了讓大家少走彎路,特來給大家分享啦

沒錯,最開始第一步當然還是引入依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

注意這裏不指定版本則與SpringBoot版本一致,以下爲我的SpringBoot版本:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.2.RELEASE</version>
    <relativePath/> 
</parent>

需要特別注意的是!!!SpringBoot2.2.2版下的freemarker源代碼做了更新,以下請看:(爲了簡潔…只保留了屬性部分,方法部分大家可以自行查看

public class FreeMarkerProperties extends AbstractTemplateViewResolverProperties {
    public static final String DEFAULT_TEMPLATE_LOADER_PATH = "classpath:/templates/";
    public static final String DEFAULT_PREFIX = "";
    public static final String DEFAULT_SUFFIX = ".ftlh";
    private Map<String, String> settings = new HashMap();
    private String[] templateLoaderPath = new String[]{"classpath:/templates/"};
    private boolean preferFileSystemAccess = true;
  }

從以上屬性值的初始化來看,suffix後綴改爲了ftlh,意味着如果我們不指定,默認後綴就爲ftlh(我在這裏真的踩了好大一坑…
由於默認路徑已經指定好了,如果我們的目錄是以下結構,就不需要再進行設定了
在這裏插入圖片描述
因此,yml文件配置如下:

spring:
  freemarker:
    suffix: .ftl

配置好了依賴和yml文件之後,就可以來寫代碼啦,以下先介紹一個簡單的例子:
真的沒有更簡單的例子了…我覺得沒有了…
controller如下:

@RequestMapping(value = "/get",method = RequestMethod.GET)
public String get(){
    return "hello";
}

ftl文件如下

<h1>hello world</h1>

沒錯 還是萬年hello world 而且ftl文件內部不需要加任何文件頭呢…下面就是頁面展示啦
在這裏插入圖片描述
到這裏,SpringBoot與freemarker的整合就結束啦,有疑問或者出了問題的歡迎評論區O

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