SpringBoot整合Freemarker實(shí)現(xiàn)頁面靜態(tài)化的詳細(xì)步驟
第一步:創(chuàng)建項(xiàng)目添加依賴:
<!--web和actuator(圖形監(jiān)控用)基本上都是一起出現(xiàn)的-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
第二步:修改application.yml文件:
spring:
freemarker:
charset: UTF-8 #設(shè)定Template的編碼
suffix: .ftl #后綴名
template-loader-path: classpath:/templates/ #模板加載路徑,多個(gè)以逗號(hào)分隔,默認(rèn): [“classpath:/templates/”]
cache: false #緩存配置,是否開啟template caching
enabled: true #是否允許mvc使用freemarker
第三步:在resources/templates目錄下創(chuàng)建模板文件index.ftl:
<html>
<head>
<title>${title}</title>
</head>
<body>
<h2>${msg}</h2>
</body>
</html>
第四步:創(chuàng)建代碼靜態(tài)化工具類:
@Component
public class GenUtil {
//創(chuàng)建Freemarker配置實(shí)例
@Resource
private Configuration configuration;
/**
* 根據(jù)模板,利用提供的數(shù)據(jù),生成文件
*
* @param sourceFile 模板文件,帶路徑
* @param data 數(shù)據(jù)
* @param aimFile 最終生成的文件,若不帶路徑,則生成到當(dāng)前項(xiàng)目的根目錄中
*/
public void gen(String sourceFile, String aimFile, Map<String, Object> data) {
try {
//加載模板文件
Template template = configuration.getTemplate(sourceFile);
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(aimFile), StandardCharsets.UTF_8));
template.process(data, out);
out.flush();
out.close();
} catch (IOException | TemplateException e) {
e.printStackTrace();
}
}
}
第五步:靜態(tài)化測試
@SpringBootTest
public class GenTest {
@Resource
private GenUtil genUtil;
@Test
void fun(){
Map<String, Object> map = new HashMap<>();
map.put("title", "首頁");
map.put("msg", "好好學(xué)習(xí),天天向上!");
FreemarkerUtil.execute("index.ftl", "haha.html", map);
}
}
測試
運(yùn)行測試代碼發(fā)現(xiàn)在當(dāng)前項(xiàng)目根目錄下生成了一個(gè)haha.html的文件。
到此這篇關(guān)于SpringBoot整合Freemarker實(shí)現(xiàn)頁面靜態(tài)化的文章就介紹到這了,更多相關(guān)SpringBoot整合Freemarker內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于Mybatis使用collection分頁問題
項(xiàng)目中mybatis分頁的場景是非常高頻的,當(dāng)使用ResultMap并配置collection做分頁的時(shí)候,我們可能會(huì)遇到獲取當(dāng)前頁的數(shù)據(jù)少于每頁大小的數(shù)據(jù)問題。接下來通過本文給大家介紹Mybatis使用collection分頁問題,感興趣的朋友一起看看吧2021-11-11
Mybatis查詢返回兩個(gè)或多個(gè)參數(shù)問題
這篇文章主要介紹了Mybatis查詢返回兩個(gè)或多個(gè)參數(shù)問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06
Java 獲取兩個(gè)List的交集和差集,以及應(yīng)用場景操作
這篇文章主要介紹了Java 獲取兩個(gè)List的交集和差集,以及應(yīng)用場景操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
Mybatis入門教程(四)之mybatis動(dòng)態(tài)sql
這篇文章主要介紹了Mybatis入門教程(四)之mybatis動(dòng)態(tài)sql的相關(guān)資料,涉及到動(dòng)態(tài)sql及動(dòng)態(tài)sql的作用知識(shí),本文介紹的非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-09-09

