在上一篇文章“SpringBoot整合視圖技術:JSP篇”我給大家簡單分享了一下在SpringBoot應用中如何使用JSP。今天,與大家分享的話題是如何整合Freemarker。
人不狠,話也不多!開擼~
1、在pom.xml文件中添加依賴,如下:
<dependencies>
<!-- web組件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- freemarker組件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemaker</artifactId>
</dependency>
</dependencies>
2、修改SpringBoot核心配置文件application.yml,如下:
server:
port: 80
spring:
freemarker:
cache: false #開發時建議關閉緩存
charset: utf-8
check-template-location: true
content-type: text/html
enabled: true
suffix: .ftl
template-loader-path: classpath:/templates #配置模板所在目錄
注意,在這裏爲了方便訪問,我修改了端口號。
3、編寫用於測試我們頁面的的控制器,如下:
/**
* @Description Freemarker測試
* @Auther: 笑笑是一個碼農
* @Date: 21:18 2019/11/4
*/
@Controller
public class FreemarkerController {
private static final String INDEX_PAGE = "index";
/**
* 跳轉測試頁面控制器
* @param map
* @return
*/
@GetMapping(value = "/index")
public String index(Map<String, String> map){
map.put("username","笑笑是一個碼農");
return INDEX_PAGE;
}
}
4、編寫測試頁面index.ftl
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Freemarker</title>
</head>
<body>
<h1>${username}</h1>
</body>
</html>
僅僅是測試使用,我們的頁面也不需要太過複雜,直接把值取出來展示即可。
5、最終的項目結構如下:
6、啓動我們的SpringBoot應用,訪問http://localhost/index,如下:
到此,我們我們就可以在SpringBoot應用中初步使用Freemarker了!
源碼鏈接:
https://github.com/devilyang123/SpringBoot-Learning/tree/master/springboot-freemarker
歡迎關注我的個人公衆號“笑笑是一個碼農”,第一時間獲取最新文章。
您的關注,就是支持我持續寫作的最大動力!
還可以免費領取前後端全站學習視頻資料呦~
個人微信號,如需添加微信,請備註來源,因爲媽媽從小就告訴我不要隨便跟陌生人聊天!(嘿嘿~)