SpringBoot系列:Spring Boot使用模板引擎FreeMarker

1、Java模板引擎

模板引擎(這裏特指用於Web開發的模板引擎)是爲了使用戶界面與業務數據(內容)分離而產生的,它能夠生成特定格式的文檔,用於網站的模板引擎就會生成一個標準的HTML文檔。html

在java中,主要的模板引擎有JSP、Thymeleaf、FreeMarker、 Velocity等。java

雖然隨着先後端分離的崛起和流行,模板引擎已遭受到冷落,但很多舊項目依然使用java的模板引擎渲染界面,而偶爾本身寫一些練手項目,使用模板引擎也比起先後端分離要來的快速。git

本系列會分別講解SpringBoot怎麼集成JSP、Thymeleaf和FreeMarker,至於Velocity,高版本的SpringBoot已經不支持Velocity了,這裏也就不進行講解了。github

而這一篇,主要講解Spring Boot如何集成FreeMarker。web

1、Spring Boot集成FreeMarker

首先咱們要引入依賴,除了核心的web依賴外,只需引入freemarker的statrer便可。spring

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

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

而後就是配置文件了。主要配置spring.freemarker節點下的視圖文件目錄template-loader-path以及文件後綴suffix,若是是本地開發,cache能夠設置爲false關閉緩存,避免修改文件後須要從新啓動服務。後端

server:
  port: 10900

spring:
  profiles:
    active: dev
  freemarker:
    enabled: true #是否啓用freemarker
    template-loader-path: classpath:/templates/ #設定模板的加載路徑,多個以逗號分隔
    suffix: .ftl #設定模板的後綴
    content-type: text/html
    check-template-location: true #是否檢查模板位置是否存在
    cache: false #是否啓用模板緩存
    charset: UTF-8 #模板編碼
    #一些經常使用配置
    allow-request-override: false #是否容許HttpServletRequest屬性覆蓋(隱藏)控制器生成的同名模型屬性
    allow-session-override: false #是否容許HttpSession屬性覆蓋(隱藏)控制器生成的同名模型屬性
    expose-request-attributes: false #設定全部request的屬性在merge到模板的時候,是否要都添加到model中
    expose-session-attributes: false #是否在merge模板的時候,將HttpSession屬性都添加到model中
    expose-spring-macro-helpers: true #設定是否以springMacroRequestContext的形式暴露RequestContext給Spring’s macro library使用
    prefer-file-system-access: true #是否優先從文件系統加載template,以支持熱加載,默認爲true

而後resoucres目錄下新建templates目錄,分別新建了hello.ftl和mv.ftl文件。緩存

<h3>hello freemarker</h3>
<!DOCTYPE html>
<html lang="en">
    <h3>mv freemarker</h3>
    <span>I'm ${name} from mv method</span>
</html>

這裏主要講解如何集成FreeMarker,不對FreeMarker語法作過多的講解,因此僅僅提供了兩個簡單的html文件做爲演示。springboot

接着再建立Controller類路由頁面,該類十分簡單,跳轉hello頁面,以及攜帶name=imyang跳轉mv頁面。session

@Controller
@RequestMapping("index")
public class IndexApi {

    @RequestMapping("/hello")
    public String hello(){
        return "hello";
    }

    @RequestMapping("/mv")
    public ModelAndView mv(){
        ModelAndView mv = new ModelAndView("mv");
        mv.addObject("name","yanger");
        return mv;
    }

}

啓動項目,分別訪問http://localhost:10900/index/hello和http://localhost:10900/index/mv,能夠看到已經能夠展現頁面信息了。

源碼地址:https://github.com/imyanger/springboot-project/tree/master/p19-springboot-freemarker

相關文章
相關標籤/搜索