Apache官网对FreeMarker的解释如下:
Apache FreeMarker™是一个模板引擎 :一个基于模板和变化的数据来生成文本输出(HTML网页,电子邮件,配置文件,源代码,等等)的Java库。
模板是用FreeMarker模板语言(FTL)编写的,这是一种简单的专业语言(不是像PHP那样成熟的编程语言)。 通常,使用通用编程语言(如Java)来准
备数据(发出数据库查询、进行业务计算)。然后,Apache FreeMarker使用模板显示准备好的数据。在模板中,您关注的是如何显示数据,而在模
板 之外,您关注的是要显示什么数据。
这种方法通常被称为MVC (Model View Controller)模式,尤其适用于动态web页面。它有助于将web页面设计人员(HTML作者)和开发人员(通
常是Java程序员)分离开来。设计人员不会在模板中面对复杂的逻辑,而且可以在不需要程序员更改或重新编译代码的情况下更改页面的外观。
虽然FreeMarker最初是为在MVC web应用程序框架中生成HTML页面而创建的,但它并不绑定到servlet或HTML或任何与web相关的东西。它
也用于非web应用程序环境。
特点:
FreeMarker的亮点:
-
-
- 强大的模板语言:条件块、迭代、赋值、字符串和算术操作和格式、宏和函数,包括其他模板、缺省转义(可选)等等
- 多用途和轻量级:零依赖,任何输出格式,可以从任何地方加载模板(可插拔),许多配置选项
- 智能的国际化和本地化:本地化敏感的数字和日期/时间格式,本地化的模板变化。
- XML处理功能:将XML DOM-s放入数据模型并遍历它们,甚至以声明的方式处理它们
-
在idea上新建springboot项目,添加如下依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
appliaction.properties配置文件 :
#端口号 server.port=8087 #ftl文件路径 spring.freemarker.template-loader-path=classpath:/templates/
temlpates下新建 freemaker.ftl 文件
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <title>Hello FreeMaker!</title> </head> <body> <p> welcome ${name} to freemarker! </p> <p>性别: <#if sex==0> 女 <#elseif sex==1> 男 <#else> 保密 </#if> </p> <h4>我的好友:</h4> <#list friends as item> 姓名:${item.name} , 年龄${item.age} <br> </#list> </body> </html>
Controller如下:
@Controller public class StudentController { @RequestMapping("testFreeMaker") public String student(Map<String,Object> map){ map.put("name", "Eminem"); map.put("sex", 1); //sex:性别,1:男;0:女; List<Map<String, Object>> friends = new ArrayList<Map<String, Object>>(); Map<String, Object> friend = new HashMap<String, Object>(); friend.put("name", "Dr.Dre"); friend.put("age", 53); friends.add(friend); friend = new HashMap<String, Object>(); friend.put("name", "Skylar Grey"); friend.put("age", 32); friends.add(friend); map.put("friends", friends); return "freemaker"; }
启动项目,访问:http://localhost:8087/testFreeMaker
、
代码地址:https://github.com/liuchunbo24/SpringBoot_FreeMarker_Demo