初試SpringBoot 的模板引擎(freemarker )

SpringBoot 使用 freemarker 模板引擎

初試SpringBoot 的模板引擎(freemarker )

快速構建freemarker 模板引擎

簡單5步起,就實現模板引擎開始:

  • 1、引入依賴包。
  • 2、設置配置文件。
  • 3、編輯後臺代碼。
  • 4、編輯前端代碼。
  • 5、啟動項目訪問。

構建步驟

1、SpringBoot 的 pom.xml 引入 freemarker 依賴包

SpringBoot默認提供了freemarker的Starter,只需簡單引入依賴即可。

 <dependency>
\t\t\t\t<groupid>org.springframework.boot/<groupid>
\t\t\t\t<artifactid>spring-boot-starter-freemarker/<artifactid>
\t\t\t/<dependency>\t\t

版本號根據SpringBoot的版本號,引用的版本不一樣。本教程使用SpringBoot 2.1.5.RELEASE 版本,默認使用2.3.28版本。


2、SpringBoot 設置配置文件

本教程使用了yml來配置SpringBoot的配置文件,使用三個配置文件。開發環境和生產環境都需要添加。配置文件可以參考:

spring:
#模板配置
freemarker:
allow-request-override: false
cache: false #是否開啟緩存,生成環境建議開啟
check-template-location: true
charset: UTF-8 #編碼
content-type: text/html; charset=utf-8 #content-type類型
expose-request-attributes: false #設定所有request的屬性在merge到模板的時候,是否要都添加到model中
expose-session-attributes: false #設定所有HttpSession的屬性在merge到模板的時候,是否要都添加到model中.
expose-spring-macro-helpers: false #RequestContext屬性的名稱
suffix: .html #模板後綴
template-loader-path: classpath:/theme/fm #模版存放路徑

# allow-session-override: false # 是否允許HttpSession屬性覆蓋(隱藏)控制器生成的同名模型屬性。
# enabled: true # 是否為此技術啟用MVC視圖解析。
# prefer-file-system-access: true # 通過文件系統訪問,可以熱檢測模板更改。
# prefix: # 前綴,用於在構建URL時查看名稱。
# request-context-attribute: # 所有視圖的RequestContext屬性的名稱。
# settings.*: # 眾所周知的FreeMarker密鑰,這些密鑰已傳遞到FreeMarker的配置中。
# view-names: # 可以解析的視圖名稱的白名單。

3、SpringBoot 編輯後臺代碼

實現一個文章來當例子:

package com.mainboot.mainbootAdmin.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mainboot.mainbootAdmin.model.Article;
import com.mainboot.mainbootAdmin.service.ArticleService;

@Controller
@RequestMapping("article")
public class ArticleViewController {

\t@Autowired
\tprivate ArticleService articleService;
\t
\t@RequestMapping("index")
\tpublic String index(Integer id,Model mv){
\t\tArticle article = new Article();
\t\tif(id!=null){
\t\t\tarticle = articleService.findId(id);
\t\t}
\t\tmv.addAttribute("article", article);
\t\treturn "index";
\t}
\t
\t
\t
}

4、SpringBoot 編輯前端代碼





<title>


${article.title}


${article.info}




5、SpringBoot 啟動項目訪問

運行項目:訪問:url/article/index?id=3056

初試SpringBoot 的模板引擎(freemarker )


希望我的分享可以幫助到你,如果你在內容技術上遇到難題,可以+關注■@主引教程 ,反饋給我們。我們會及時回覆,如果有那些內容有誤可以直接提出來,我們會及時糾正,謝謝來訪。


分享到:


相關文章: