
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency><!DOCTYPE html>
<html lang="en" xmlns="https://freemarker.apache.org/">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<span>${username}</span>
</body>
</html>使用模板分别输出到文件和变量
补充直接内存中定义字符串模板
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import java.io.*;
import java.nio.Buffer;
import java.util.HashMap;
public class FreemarkerDemo {
public static void main(String[] args) throws IOException, TemplateException {
// http://freemarker.foofun.cn/pgui_quickstart_createconfiguration.html
// 创建配置实例 !!不需要重复创建 Configuration 实例; 它的代价很高,尤其是会丢失缓存。Configuration 实例就是应用级别的单例。
Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
// 设置配置实例信息
cfg.setDirectoryForTemplateLoading(new File(ClassLoader.getSystemResource("template").getPath()));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
// 获取模板
Template template = cfg.getTemplate("test.ftl");
// 创建数据模型
HashMap<String,Object> map = new HashMap<>();
map.put("username","张三");
Writer out = new FileWriter("e:\\freemarker_test_out.html");
// 渲染模板 输出到文件
template.process(map,out);
// 资源关闭
out.flush();
out.close();
// 渲染模板 输出到变量
StringWriter reslut = new StringWriter();
template.process(map,reslut);
System.out.println(reslut.toString());
}
/**
* 自定义字符串模板
*/
@Test
public void processString() throws IOException, TemplateException {
// 创建配置实例 !!不需要重复创建 Configuration 实例; 它的代价很高,尤其是会丢失缓存。Configuration 实例就是应用级别的单例。
Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
// 设置配置实例信息
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
// 注册模板
stringTemplateLoader.putTemplate("test.ftl","${username},你好");
cfg.setTemplateLoader(stringTemplateLoader);
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
// 获取模板
Template template = cfg.getTemplate("test.ftl","UTF-8");
// 创建数据模型
HashMap<String,Object> map = new HashMap<>();
map.put("username","张三");
// 渲染模板 输出到变量
StringWriter reslut = new StringWriter();
template.process(map,reslut);
System.out.println(reslut.toString());
}
}
控制台输出

输出到文件
