SpringBoot整合Freemarker實現頁面靜態(tài)化的詳細步驟
第一步:創(chuàng)建項目添加依賴:
<!--web和actuator(圖形監(jiā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 #設定Template的編碼
suffix: .ftl #后綴名
template-loader-path: classpath:/templates/ #模板加載路徑,多個以逗號分隔,默認: [“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配置實例
@Resource
private Configuration configuration;
/**
* 根據模板,利用提供的數據,生成文件
*
* @param sourceFile 模板文件,帶路徑
* @param data 數據
* @param aimFile 最終生成的文件,若不帶路徑,則生成到當前項目的根目錄中
*/
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", "好好學習,天天向上!");
FreemarkerUtil.execute("index.ftl", "haha.html", map);
}
}
測試
運行測試代碼發(fā)現在當前項目根目錄下生成了一個haha.html的文件。
到此這篇關于SpringBoot整合Freemarker實現頁面靜態(tài)化的文章就介紹到這了,更多相關SpringBoot整合Freemarker內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決Spring配置文件中bean的property屬性中的name出錯問題
這篇文章主要介紹了解決Spring配置文件中bean的property屬性中的name出錯問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
springMVC中@RequestParam和@RequestPart的區(qū)別
本文主要介紹了springMVC中@RequestParam和@RequestPart的區(qū)別,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2024-06-06
Maven發(fā)布封裝到中央倉庫時候報錯:no default secret key
這篇文章主要介紹了Maven發(fā)布封裝到中央倉庫時候報錯:no default secret key,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-12-12

