1. 程式人生 > >最簡單的freemarker用法例項

最簡單的freemarker用法例項

     

1.下載freemarker-2.3.19.jar到web專案的lib下。

2.新建freemarker引擎協助類

package com.bxsurvey.sys.process.util;

import java.io.StringWriter;

import java.util.Map;

import freemarker.template.Configuration;

import freemarker.template.Template;

/**

*

* @Title:FreemarkerHelper

* @description:Freemarker引擎協助類

* @date Jul 5, 2013 2:58:29 PM

* @version V1.0

*/

public class FreemarkerHelper {

private static Configuration _tplConfig = new Configuration();

static{

_tplConfig.setClassForTemplateLoading(FreemarkerHelper.class, "/");

}

/**

* 解析ftl

* @param tplName 模板名

* @param encoding 編碼

* @param paras 引數

* @return

*/

public String parseTemplate(String tplName, String encoding,

Map<String, Object> paras) {

try {

StringWriter swriter = new StringWriter();

Template mytpl = null;

mytpl = _tplConfig.getTemplate(tplName, encoding);

mytpl.process(paras, swriter);

return swriter.toString();

} catch (Exception e) {

e.printStackTrace();

return e.toString();

}

}

public String parseTemplate(String tplName, Map<String, Object> paras) {

return this.parseTemplate(tplName, "utf-8", paras);

}

}

3.新建autolist.ftl檔案。放置在com/bxsurvey/sys/process/tabletemplate/autolist.ftl

<html lang="en">

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

</head>

<body>

${tableName?if_exists?html}

</body>

 

 

 

</html>

 

4.使用方法,方法listView方法就可以在瀏覽器中顯示ftl頁面的內容

@RequestMapping(params = "listView")

public void listView(HttpServletRequest request,HttpServletResponse response) {

//獲取列表ftl模板路徑

FreemarkerHelper viewEngine = new FreemarkerHelper();

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

paras.put("tableName","表名");

//組合模板+資料引數,進行頁面展現

String html = viewEngine.parseTemplate("/com/bxsurvey/sys/process/tabletemplate/autolist.ftl", paras);

try {

response.setContentType("text/html;charset=utf-8");

response.setHeader("Cache-Control", "no-store");

PrintWriter writer = response.getWriter();

writer.println(html);

writer.flush();

} catch (IOException e) {

e.printStackTrace();

}

}