Java工程中使用freemarker例子

发表于:2016-4-26 11:02

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:疯子110    来源:51Testing软件测试网采编

  新建java project,引入freemarker.jar, 本工程是用的版本:freemarker-2.3.20 版本
  java工程目录如下:
  test.ftl文件
name : ${name}
age : ${age}
test类
package com.freemarker;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class Test {
public static void main(String[] args) throws IOException, TemplateException {
//1.创建配置实例Cofiguration
Configuration cfg = new Configuration();
//2.设置模板文件目录
//(1)src目录下的目录(template在src下)
//cfg.setDirectoryForTemplateLoading(new File("src/template"));
//(2)完整路径(template在src下)
//cfg.setDirectoryForTemplateLoading(new File(
//      "D:/cpic-env/workspace/javaFreemarker/src/template"));
//cfg.setDirectoryForTemplateLoading(new File("src/template"));
//(3)工程目录下的目录(template/main在工程下)--推荐
cfg.setDirectoryForTemplateLoading(new File("template/main"));
//cfg.setObjectWrapper(new DefaultObjectWrapper());
//获取模板(template)
Template template = cfg.getTemplate("test.ftl");
//建立数据模型(Map)
Map<String, String> root = new HashMap<String, String>();
root.put("name", "cxl");
root.put("age", "25");
//获取输出流(指定到控制台(标准输出))
Writer out = new OutputStreamWriter(System.out);
//StringWriter out = new StringWriter();
//System.out.println(out.toString());
//数据与模板合并(数据+模板=输出)
template.process(root, out);
out.flush();
}
}
  运行结果:
  name : cxl
  age : 25
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号