资料引入依赖定义模板使用附
1. 工程结构示例2. 执行结果示例3. 示例源码
资料官网
中文版
定义模板org.freemarker freemarker 2.3.31
Title
${username}
使用
使用模板分别输出到文件和变量
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 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());
}
}
附
1. 工程结构示例
2. 执行结果示例
控制台输出
输出到文件
https://gitee.com/master336/template-engine-demo


![[模板引擎] freemarker独立环境使用 [模板引擎] freemarker独立环境使用](http://www.mshxw.com/aiimages/31/721119.png)
