玩轉 SpringBoot 2 快速整合 | FreeMarker篇


FreeMarker 介紹

Apache FreeMarker™是一個模板引擎:一個Java庫,用於根據模板和更改數據生成文本輸出(HTML網頁,電子郵件,配置文件,源代碼等)。模板是用FreeMarker模板語言(FTL)編寫的,這是一種簡單的專用語言(不像PHP這樣的完整編程語言)。通常,使用通用編程語言(如Java)來准備數據(發布數據庫查詢,進行業務計算)。然后,Apache FreeMarker使用模板顯示准備好的數據。在模板中,您將專注於如何呈現數據,而在模板之外,您將關注於要呈現的數據。

圖片

SpringBoot 官方比較推薦使用 Thymeleaf,由於自己對 FreeMarker 相對比較熟悉,所以這里我先介紹一下如何在 SpringBoot 中使用 FreeMarker 當前前端頁面使用。
                                                                                  ——以上內容摘抄自 FreeMarker 官網

SpringBoot 使用 FreeMarker 操作步驟

第一步是在pom.xml 中引入 spring-boot-starter-freemarker 依賴具體代碼如下:

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

第二步是在resources 下 templates 創建test目錄新建 freemarkDemo.ftl 內容如下:

<h1>${msg}</h1>

第三步是創建訪問 freemarkDemo.ftl 的Controller。


@Controller
@RequestMapping("/hello")
public class HelloWorldController {
	@RequestMapping("/test")
    public String test(Model model){
		model.addAttribute("msg", "SpringBoot With Freemark hello world!");
        return "test/helloworld";
    }
}

測試

在游覽器輸入訪問 FreeMarker 頁面的 Controller 的 URL:http://localhost:8080/sbe/hello/test   進行測試,測試結果如下:

file

小結

SpringBoot 使用 FreeMarker 步驟如下:

  1. 添加 FreeMarker starter依賴
  2. 創建模版頁面和訪模版問頁面Controller

代碼示例

具體代碼示例請查看我的 GitHub 倉庫 springbootexamples 中模塊工程名: spring-boot-2.x-freemarker 下進行查看。

GitHub:https://github.com/zhuoqianmingyue/springbootexamples


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM