Freemarker 入门程序

jar 包:freemarker-gae-2.3.19

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreemarkerDemo {

	public static void main(String[] args) throws IOException, TemplateException {
		// 创建freemarker实例
		Configuration conf = new Configuration();
		// 设置模版 路径
		String dir = "E:\\ws\\framework\\demo\\ftl\\";
		// 设置模板的加载目录,这个路径必须写成绝对路径。
		// 但是在实际的项目开发中,我们不可能使用这样一个路径,
		// 因此,我们需要借助其他方法,例如springmvc中有FreeMarkerConfigurer这样的一个类
		conf.setDirectoryForTemplateLoading(new File(dir));
		// 设置将 [#]替代<#ftl>
		conf.setTagSyntax(Configuration.SQUARE_BRACKET_TAG_SYNTAX);
		// 指定模板,返回模板对象
		Template template = conf.getTemplate("freemarker.html");
		// 设置数据
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("world", "你好世界");
		root.put("cur_time", new Date());
		Person person = new Person();
		person.setName("张三");
		Person person1 = new Person();
		root.put("person", person);
		root.put("person1", person1);
		// 输出
		Writer out = new FileWriter(new File(dir + "hello.html"));
		// freemarker处理数据及模板并输出
		template.process(root, out);
		out.close();

	}
}

模板:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
${world}

[#assign x ]
	[#list ["1","2","3"] as n]
		${n}
	[/#list]
[/#assign]
${x+2}

${person.name}
${person1.name!".."}

${cur_time?string('yyyy-MM-dd')}

[#macro macroName source]
${source}
[/#macro]
[@macroName source=2 /]

</body>
</html>

生成的文件:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
你好世界

		1
		2
		3
2

张三
..

2017-05-11

2

</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值