在真正的学习之前,应该明白这个一些前置的准备工作
1.Maven依赖
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
2.fts后缀文件
该文件为html模板文件,定义了html最后是以什么格式渲染出来,本质上就是使用了占位符,class转递参数过来渲染再将整个源码回馈给class
![[Pasted image 20241229134917.png]]
这是一个最常见的且最简单的例子,其中
${key} 是一个键值对的体现,通过这个方式可以实现在html中占位以及获取到Key的操作、
<#list items as item><#list> 这个就跟python的写法差不多了,是一个循环,items是容器,item是迭代项
开始使用FreeMarker
1.配置FreeMarker
Configuration cfg = new Configuration(Configuration.VERSION_2_3_31); // 创建并配置版本号
cfg.setDirectoryForTemplateLoading(new File("src/main/java/org/example")); // 指定模板文件所在文件夹路径
cfg.setDefaultEncoding("UTF-8"); // 设置读取输出的默认编码
2.加载模板
Template template = cfg.getTemplate("template.ftl"); // 基于上面的文件夹路径中的模板文件
3.准备数据模型
Map<String, Object> data = new HashMap<>(); // 创建一个map来存储键值对数据,key对应模板中的key,最后在模板中放入的是Key读取的是值
data.put("title", "Example Website");
data.put("header", "Welcome to my website!");
data.put("content", "This is an example of a FreeMarker app.");
data.put("items", list.of("数据1","数据2")); // jdk9引入的新创建list的方式
4.处理模板
StringWriter out = new StringWriter(); //通常用于在内存中捕获和存储输出,用于存储模板处理后的输出
template.process(data, out); // 将数据模型和输出流传递给模板引擎,模板引擎将根据模板文件和数据模型生成HTML内容
String html = out.toString();// 到这步html输出的就是一个渲染好数据的的html模板代码
5.使用io流写入数据,创建html文件
BufferedWriter bw = new Buffered(new FileWriter("test.html"));
bw.write(html); // 利用直接写入字符串的特性
bw.close
完整代码
创建一个template.ftl文件
<#--html模板-->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>${title}</title>
</head>
<body>
<h1>${header}</h1>
<p>${content}</p>
<ul>
<#list items as item>
<li>${item}</li>
</#list>
</ul>
<p>${aichat}</p>
</body>
</html>
在main方法执行
package org.example;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.*;
public class Main {
public static void main(String[] args) {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
try {
cfg.setDirectoryForTemplateLoading(new File("src/main/java/org/example"));
cfg.setDefaultEncoding("UTF-8");
Template template = cfg.getTemplate("template.ftl");
Map<String, Object> data = new HashMap<>();
data.put("title", "Example Website");
data.put("header", "Welcome to my website!");
data.put("content", "This is an example of a FreeMarker app.");
data.put("items", List.of("数据1","数据2"));
StringWriter out = new StringWriter();
template.process(data, out);
String html = out.toString();
// io写入创建html文件
File file = new File("test.html");
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
bw.write(html);
bw.close();
} catch (IOException | TemplateException e) {
e.printStackTrace();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}