码上敲享录 > java入门知识分享 > 最简单的freemarker用法实例

最简单的freemarker用法实例

上一章章节目录下一章 2017-11-01已有2904人阅读 评论(0)

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

}

}

本文地址:http://yayihouse.com/yayishuwu/chapter/1015

1

有建议,请留言!

  • *您的姓名:

  • *所在城市:

  • *您的联系电话:

    *您的QQ:

  • 咨询问题:

  • 提 交