一、pom 文件引入FreeMarker
在原 SpringBoot 項目中的 POM 文件中加入 FreeMarker 座標,如果不知道座標可以從 Maven 中央庫查詢 http://mvnrepository.com/。當然,如果項目沒有使用 Maven ,那就需要導入 FreeMarker Jar ,點擊下載JAR ,此外還需要有 spring-context-support.jar
。
<!-- 引入freeMarker的依賴包. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
二、Controller
package com.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.bean.User;
/**
* @Description 測試整合freemarker
* @author 歐陽
* @since 2019年4月10日 下午3:55:10
* @version V1.0
*/
@Controller
public class IndexMarkerController {
@RequestMapping("/indexmarker")
public String indexmarker(Map<String, Object> map) {
//添加標題
map.put("title", "SpringBoot整合Freemarker");
//添加人員
List<User> result = new ArrayList<User>();
result.add(new User("1", "zhangsan"));
result.add(new User("2", "lisi"));
result.add(new User("3", "王五"));
map.put("users", result);
return "indexmarker";
}
}
注意:使用註解 @Controller
而不要使用 @RestController
,否則會將返回的視圖名解析成字符串返回到頁面。如果使用 @RestController
註解,則需要返回 ModelAndView
。
三、application.properties 配置
在 application.properties
文件中添加下面配置:
###Freemarker Configuration
spring.freemarker.allow-request-override=false
spring.freemarker.cache=true
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
spring.freemarker.suffix=.ftl
spring.freemarker.template-loader-path=classpath:/templates/
上面的配置使用 application.yml
文件配置如下:
###FREEMARKER Configuration
spring:
freemarker:
allow-request-override: false
cache: true
check-template-location: true
charset: UTF-8
content-type: text/html; charset=utf-8
expose-request-attributes: false
expose-session-attributes: false
expose-spring-macro-helpers: false
suffix: .ftl
template-loader-path:
- classpath:/templates/
四、FTL 文件
當使用 FreeMarker 模板引擎時,默認的模板配置路徑爲:src/main/resources/templates
,也可將默認配置路徑修改爲其他路徑,方法是通過修改 application.properties
文件中的 spring.freemarker.template-loader-path
屬性值。下面是模版 indexmarker.ftl
的主要代碼。關於 FreeMarker 的語法自行百度。
<body>
<#if title == "1">
<caption>標題</caption>
<#elseif title == "2">
<caption>測試</caption>
<#else>
<caption>${title}</caption>
</#if>
<table class="table table-bordered table-hover">
<thead>
<tr>
<td>序號</td>
<td>姓名</td>
</tr>
</thead>
<tbody>
<#list users as user>
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
</tr>
</#list>
</tbody>
</table>
</body>
五、整合後結果
瀏覽器訪問地址:http://localhost:8080/indexmarker,後效果圖如下: