分3步
1. jar包
freemarker-2.3.19.jar
2. 代码
package pr.cgl.freemarker; import freemarker.template.Configuration; import freemarker.template.Template; import java.io.File; import java.io.OutputStreamWriter; import java.io.StringReader; import java.util.HashMap; import java.util.Map;
public class FreemarkerTest { public static void main(String[] args) throws Exception{ //1.初始化配置 Configuration cfg = new Configuration(); //2.创建插值的model数据对象 Map map = new HashMap(); map.put("user", "lavasoft"); map.put("url", "http://www.baidu.com/"); map.put("name", "百度"); //3.加载模板文件 File templateDir = new File(FreemarkerTest.class.getResource("").getPath()); cfg.setDirectoryForTemplateLoading(templateDir); Template tt = cfg.getTemplate("index.ftl"); //4.生成目标页面文件并输出 tt.process(map, new OutputStreamWriter(System.out)); } } 3. 运行结果
<!DOCTYPE html>
<html><head lang="en"> <meta charset="UTF-8"> <title></title></head><body>Hello, lavasoft,请访问<a href="http://www.baidu.com/">百度</a>
</body></html>