生活随笔
收集整理的這篇文章主要介紹了
获取freemarker处理后的内容
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? 相信很多人都用過freemarker,或做視圖,或模板,或生成靜態文件等,但是有多少人做過這樣的應用,通過模板后,不是要輸出靜態的內容,而是直接在代碼中獲取處理模板后的內容,研究了下API,freemarker里提供StringWriter,StringWriter不需要指定文件,所以看名字也能知道,他能直接獲取處理后的內容,代碼如下?
Java代碼??
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");?? ?????????? ?????????? ????????StringWriter?stringWriter=new?StringWriter();?? ?????????? ????????try?? ????????{?? ????????????t.process(root,?stringWriter);?? ?????????????? ?????????????? ????????????System.out.println("stringWriter:?"+stringWriter.toString());?? ????????}?catch?(TemplateException?e)?? ????????{?? ????????????e.printStackTrace();?? ????????}?? ?? ????}?? ?? }??
test.txt模板里的內容如下:?
Java代碼??
${message}?? ${username}?? ?? ${strList?size}?? ?? <#list?strList?as?str>?? ????str:${str};?哈哈?? </#list>??
總結
以上是生活随笔為你收集整理的获取freemarker处理后的内容的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。