SpringBoot整合Freemarker實現(xiàn)頁面靜態(tài)化的詳細步驟
更新時間:2022年10月26日 09:13:46 作者:梁云亮
這篇文章主要介紹了SpringBoot整合Freemarker實現(xiàn)頁面靜態(tài)化,第一步要創(chuàng)建項目添加依賴,本文分步驟給大家詳細講解,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
第一步:創(chuà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 #設定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; /** * 根據(jù)模板,利用提供的數(shù)據(jù),生成文件 * * @param sourceFile 模板文件,帶路徑 * @param data 數(shù)據(jù) * @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ā)現(xiàn)在當前項目根目錄下生成了一個haha.html的文件。
到此這篇關于SpringBoot整合Freemarker實現(xiàn)頁面靜態(tài)化的文章就介紹到這了,更多相關SpringBoot整合Freemarker內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Mybatis入門教程(四)之mybatis動態(tài)sql
這篇文章主要介紹了Mybatis入門教程(四)之mybatis動態(tài)sql的相關資料,涉及到動態(tài)sql及動態(tài)sql的作用知識,本文介紹的非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-09-09