创建一个Maven工程:
工程目录如下:
在pom.xml中添加 freemarker -x.x.x 的依赖:
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.20</version>
</dependency>
测试的 ftl 模板文件如下 - test.ftl:
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome ${user}!</h1>
<p>Our latest product:
<a href="${latestProduct.url}">${latestProduct.name}</a>!
</body>
</html>
测试代码 - FreeMarkerTest
package com.gof.freemarker.test;
import java.io.File;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
public class FreeMarkerTest {
public static void main(String[] args){
Configuration cfg = new Configuration();
try{
File ftlDirFile = new File(FreeMarkerTest.class.getResource("/ftl").toURI());
cfg.setDirectoryForTemplateLoading(ftlDirFile);
cfg.setObjectWrapper(new DefaultObjectWrapper());
// create data model
Map root = new HashMap();
root.put("user", "Big Joe");
Map latest = new HashMap();
root.put("latestProduct", latest);
latest.put("url", "products/greenmouse.html");
latest.put("name", "green mouse");
//create ftl template
Template template = cfg.getTemplate("test.ftl");
// output
Writer out = new OutputStreamWriter(System.out);
template.process(root, out);
out.flush();
}catch (Exception e){
e.printStackTrace();
}
}
}
运行,输出的结果为(Console):
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome Big Joe!</h1>
<p>Our latest product:
<a href="products/greenmouse.html">green mouse</a>!
</body>
</html>
|