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();
}
}