FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页、电子邮件、配置文件、源代码等)的通用工具。 它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件。
小Demo
1.导入依赖
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
2.创建一个模板
文件后缀名为ftl,下面为举例模板并有相应的方法
说明:
标记开头都是<#
取值是用${}取值的
<html>
<head>
<meta charset="utf-8">
<title>Freemarker 入门小 DEMO </title>
</head>
<body>
<#--我只是一个注释,我不会有任何输出 -->
<#-- 取值通过${}取 -->
${name},你好。${message}
<#--定义变量-->
<#assign age=18>
我今年${age}岁
<#--导入别的模板-->
<#include "title.ftl">
<#--if else语句-->
<#if false>
我是if
<#else>
我是else
</#if>
----家里动物吃什么---
<#--遍历集合 listAnial是传的集合名-->
<#list listAnial as dongwu>
${dongwu_index+1}: 动物:${dongwu.name}吃:${dongwu.eat}
</#list>
<#--内置函数 用来获取总记录数-->
总共:${listAnial?size}条记录
<#--将json字符串转成json对象-->
<#--定义一个json字符串-->
<#assign text="{'class':'五方桥基地','name':'郭子轩'}">
<#assign data=text?eval>
班级:${data.class} 姓名:${data.name}
</body>
</html>
3.写代码
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test {
public static void main(String[] args) throws IOException, TemplateException {
//1.创建Configuration 对象
Configuration configuration = new Configuration(Configuration.getVersion());
//2. 配置模板文件地址(也就是你模板存放的位置)
configuration.setDirectoryForTemplateLoading(new File(".\\src\\main\\resources\\template"));
//3.设置字符集 准备工作 setting--File Encodings 设置成UTF-8
configuration.setDefaultEncoding("utf-8");
//4.加载模板(模板名)
Template template = configuration.getTemplate("demo.ftl");
//5.创建数据模型
Map map=new HashMap(); //回传的数据
map.put("name", "学员");
map.put("message", "欢迎来优就业学习!");
//模拟数据库读的数据集合
Map map1=new HashMap();
map1.put("name", "狗");
map1.put("eat", "骨头!");
Map map2=new HashMap();
map2.put("name", "鱼");
map2.put("eat", "虾米!");
List listAnial = new ArrayList();
listAnial.add(map1);
listAnial.add(map2);
map.put("listAnial",listAnial);
//6.输出静态页面的地址
FileWriter out = new FileWriter(new File(".\\src\\main\\resources\\demo.html"));
//7.调用模板进行渲染 这里很关键! 是给页面回传参数,这里传的是Map集合
template.process(map, out);
System.out.println("生成成功");
//关闭输出流
out.close();
}
}