天天看點

使用freemarker生成靜态頁面

 使用freemarker生成靜态頁面

開發門戶網站時,我們需要把頁面生成靜态的,以應對大規模的通路,這篇文章主要介紹了,如何使用freemarker的API将模闆檔案(ftl)生成為html檔案

建立getTemplate方法用于擷取freemarker的模闆Template 對象

public static Template getTemplate(Configuration cfg,String name) throws IOException{

     cfg.setDefaultEncoding("UTF-8");

     cfg.setNumberFormat("#");

     return cfg.getTemplate(name);

}

建立doWirte方法用于往磁盤上寫生成好的檔案

public void doWirte(Template t,String path,Map<String, Object> req){

        try {

         File staticPage = new File(path);

         if(!staticPage.exists())

         staticPage.createNewFile();

            Writer wt = new OutputStreamWriter(new FileOutputStream(staticPage), "UTF-8");

            t.setEncoding("UTF-8");

            t.process(req,wt);

        } catch (Exception e) {

            e.printStackTrace();

        }

最後建立createStaticPage方法

/**

 * 

 * createFtl:此方法用于生成靜态頁

 *

 * @param  @param req 模闆中需要的參數

 * @param  @param templatePath 模闆檔案路徑

 * @param  @param templateFileName 模闆檔案名

 * @param  @param staticPagename    靜态頁檔案名

 * @return void    DOM對象

 * @throws 

 * @since  CodingExample Ver 1.1

 */

private void createStaticPage(Map<String, Object> req,String templatePath,String templateFileName,String staticPagename){

            Configuration cfg = new Configuration();

            String tempate = getWebRoot() + templatePath;

            String destPath = getWebRoot() + staticPagename;

            cfg.setDirectoryForTemplateLoading(new File(tempate));

            Template tIndex = getTemplate(cfg,templateFileName);

            doWirte(tIndex,destPath,req);

生成靜态頁時,就按照下面生成就可以

public void createJingyanGanxiePage() {

Map<String, Object> map = new HashMap<String, Object>();

map.put("ctx", ctx);

this.createStaticPage(map,"/WEB-INF/ftl/front/","index/jingyanganxie.ftl","jingyanganxie.htm");

本文轉自 tony_action 51CTO部落格,原文連結:http://blog.51cto.com/tonyaction/676914,如需轉載請自行聯系原作者

繼續閱讀