一、Java模板引擎
模板引擎(這里特指用于Web開發(fā)的模板引擎)是為了使用戶界面與業(yè)務(wù)數(shù)據(jù)(內(nèi)容)分離而產(chǎn)生的,它可以生成特定格式的文檔,用于網(wǎng)站的模板引擎就會(huì)生成一個(gè)標(biāo)準(zhǔn)的HTML文檔。
在java中,主要的模板引擎有JSP、Thymeleaf、FreeMarker、
Velocity等。
雖然隨著前后端分離的崛起和流行,模板引擎已遭受到冷落,但不少舊項(xiàng)目依然使用java的模板引擎渲染界面,而偶爾自己寫一些練手項(xiàng)目,使用模板引擎也比起前后端分離要來的快速。
本系列會(huì)分別講解SpringBoot怎么集成JSP、Thymeleaf和FreeMarker,至于Velocity,高版本的SpringBoot已經(jīng)不支持Velocity了,這里也就不進(jìn)行講解了。
而這一篇,主要講解Spring Boot如何集成FreeMarker。
一、Spring Boot集成FreeMarker
首先我們要引入依賴,除了核心的web依賴外,只需引入freemarker的statrer即可。
<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節(jié)點(diǎn)下的視圖文件目錄template-loader-path以及文件后綴suffix,如果是本地開發(fā),cache可以設(shè)置為false關(guān)閉緩存,避免修改文件后需要重新啟動(dòng)服務(wù)。
server:
port: 10900
spring:
profiles:
active: dev
freemarker:
enabled: true #是否啟用freemarker
template-loader-path: classpath:/templates/ #設(shè)定模板的加載路徑,多個(gè)以逗號(hào)分隔
suffix: .ftl #設(shè)定模板的后綴
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 #設(shè)定所有request的屬性在merge到模板的時(shí)候,是否要都添加到model中
expose-session-attributes: false #是否在merge模板的時(shí)候,將HttpSession屬性都添加到model中
expose-spring-macro-helpers: true #設(shè)定是否以springMacroRequestContext的形式暴露RequestContext給Spring’s macro library使用
prefer-file-system-access: true #是否優(yōu)先從文件系統(tǒng)加載template,以支持熱加載,默認(rèn)為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,不對(duì)FreeMarker語法做過多的講解,所以僅僅提供了兩個(gè)簡(jiǎn)單的html文件作為演示。
接著再創(chuàng)建Controller類路由頁面,該類十分簡(jiǎn)單,跳轉(zhuǎn)hello頁面,以及攜帶name=imyang跳轉(zhuǎn)mv頁面。
@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;
}
}
啟動(dòng)項(xiàng)目,分別訪問http://localhost:10900/index/hello和http://localhost:10900/index/mv,可以看到已經(jīng)可以展示頁面信息了。

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