原文連接:http://www.yiidian.com/springboot/springboot-freemarker.htmlhtml
本文講解如何在Spring Boot整合FreeMarker。java
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.yiidian</groupId> <artifactId>ch03_05_springboot_freemarker</artifactId> <version>1.0-SNAPSHOT</version> <!-- 導入springboot父工程. 注意:任何的SpringBoot工程都必須有的!!! --> <!-- 父工程的做用:鎖定起步的依賴的版本號,並無真正到依賴 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.11.RELEASE</version> </parent> <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-freemarker</artifactId> </dependency> </dependencies> </project>
這裏記得要到FreeMarker的依賴,不然沒法運行!web
package com.yiidian.controller; import java.util.ArrayList; import java.util.List; import com.yiidian.domain.User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; /** * 控制器 * 一點教程網 - www.yiidian.com */ @Controller public class UserController { /** * 用戶列表展現 */ @RequestMapping("/list") public String list(Model model){ //模擬用戶數據 List<User> list = new ArrayList<User>(); list.add(new User(1,"小張",18)); list.add(new User(2,"小李",20)); list.add(new User(3,"小陳",22)); //把數據存入model model.addAttribute("list", list); //跳轉到freemarker頁面: list.ftl return "list"; } }
在Controller把數據傳遞到FreeMarker模板渲染spring
FreeMarker模板文件必須放在/resources/templates目錄下,後綴名爲.ftl,內容以下:apache
<html> <title>一點教程網-用戶列表展現</title> <meta charset="utf-8"/> <body> <h3>用戶列表展現</h3> <table border="1"> <tr> <th>編號</th> <th>姓名</th> <th>年齡</th> </tr> <#list list as user> <tr> <td>${user.id}</td> <td>${user.name}</td> <td>${user.age}</td> </tr> </#list> </table> </body> </html>
http://localhost:8080/listspringboot
源碼下載:https://pan.baidu.com/s/10WaOAfrWHG-v2M8QFe2zMAapp
歡迎關注個人公衆號::一點教程。得到獨家整理的學習資源和平常乾貨推送。 若是您對個人系列教程感興趣,也能夠關注個人網站:yiidian.comdom