一、通过文件来创建模版对象,并执行插值操作
文件结构为:
Test.Java中的代码为:
- package com.abc;
- import freemarker.template.Configuration;
- import freemarker.template.Template;
- import java.io.File;
- import java.io.OutputStreamWriter;
- import java.util.HashMap;
- import java.util.Map;
- public class Test {
- public static void main(String[] args) throws Exception {
- //创建一个Configuration实例
- final Configuration cfg;
- cfg = new Configuration();
- //设置FreeMarker的模版文件夹位置
- cfg.setDirectoryForTemplateLoading(new File("D:\\workspace\\freemarkertest\\src\\com\\abc"));
- Map<String, String> map = new HashMap<String, String>();
- map.put("user", "Zheng");
- map.put("website", "金额宝");
- map.put("url", "http://www.jebao.net/");
- //创建模版对象
- Template t = cfg.getTemplate("test.ftl");
- //在模版上执行插值操作,并输出到制定的输出流中
- t.process(map, new OutputStreamWriter(System.out));
- }
- }
Test.ftl中的代码为:
- <html>
- <head>
- <title>Welcome!</title>
- </head>
- <body>
- <h1>Welcome ${user}!</h1>
- <p>Our latest product:
- <a href="${url}">${website}</a>!
- </body>
- </html>
- 尊敬的用户你好!
- 用户名:${user}
- URL: ${url}
- 网站: ${website}
运行结果为:
</head>
<body>
<h1>Welcome Zheng!</h1>
<p>Our latest product:
<ahref="http://www.jebao.NET/">金额宝</a>!
</body>
</html>
尊敬的用户你好!
用户名:Zheng
URL: http://www.jebao.Net/