简单用例:
在pom.xml添加dependency
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
添加测试类
package com.mongodb;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class HelloWorldFreemakerStyle {
public static void main(String[] args){
Configuration configuration = new Configuration();
configuration.setClassForTemplateLoading(
HelloWorldFreemakerStyle.class, "/");//search for templates in classpath
try {
Template helloTemplate = configuration.getTemplate("welcome.ftl");
StringWriter writer = new StringWriter();
Map<String, Object> helloMap = new HashMap<String,Object>();
helloMap.put("name", "freemaker");
helloTemplate.process(helloMap, writer);
System.out.println(writer);
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行,控制台输出
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>hello freemaker</h1>
</body>
</html>