相信很多人都用过freemarker,或做视图,或模板,或生成静态文件等,但是有多少人做过这样的应用,通过模板后,不是要输出静态的内容,而是直接在代码中获取处理模板后的内容,研究了下API,freemarker里提供StringWriter,StringWriter不需要指定文件,所以看名字也能知道,他能直接获取处理后的内容,代码如下
- import java.io.IOException;
- import java.io.StringWriter;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import freemarker.template.Configuration;
- import freemarker.template.Template;
- import freemarker.template.TemplateException;
- public class TestFreemarker
- {
- @SuppressWarnings("unchecked")
- public static void main(String[] args) throws IOException
- {
- Configuration cfg = new Configuration();
- cfg.setDirectoryForTemplateLoading(new File("E:\\kuaipan\\workspace2016\\freemarker001\\src\\hello"));
- List<String> strList=new ArrayList<String>();
- for (int i = 0; i < 2000; i++)
- {
- strList.add("第 "+i+" 个");
- }
- Map root = new HashMap();
- root.put("message", "您好!");
- root.put("username", "diqiu");
- root.put("strList", strList);
- Template t = cfg.getTemplate("test.txt");
- //最关键在这里,不使用与文件相关的Writer
- StringWriter stringWriter=new StringWriter();
- try
- {
- t.process(root, stringWriter);
- //这里打印的就是通过模板处理后得到的字符串内容
- System.out.println("stringWriter: "+stringWriter.toString());
- } catch (TemplateException e)
- {
- e.printStackTrace();
- }
- }
- }
test.txt模板里的内容如下:
- ${message}
- ${username}
- ${strList?size}
- <#list strList as str>
- str:${str}; 哈哈
- </#list>