新建java project,引入freemarker.jar, 本工程是用的版本:freemarker-2.3.20 版本java
java工程目錄以下:
app
test.ftl文件spa
- name : ${name}
- age : ${age}
test類3d
- package com.freemarker;
-
- import java.io.File;
- import java.io.IOException;
- import java.io.OutputStreamWriter;
- import java.io.Writer;
- import java.util.HashMap;
- import java.util.Map;
-
- import freemarker.template.Configuration;
- import freemarker.template.Template;
- import freemarker.template.TemplateException;
-
- public class Test {
- public static void main(String[] args) throws IOException, TemplateException {
-
-
- Configuration cfg = new Configuration();
-
-
-
-
-
-
-
-
-
- cfg.setDirectoryForTemplateLoading(new File("template/main"));
-
-
- Template template = cfg.getTemplate("test.ftl");
-
- Map<String, String> root = new HashMap<String, String>();
- root.put("name", "cxl");
- root.put("age", "25");
-
- Writer out = new OutputStreamWriter(System.out);
-
-
-
- template.process(root, out);
- out.flush();
- }
- }
運行結果:xml