---
title: "Freemarker模板应用"
author: "ansn001"
date: "2012-07-23T22:38:33Z"
tags: ["ftl"]
categories: ["编程语言"]
slug: "freemarker"
draft: false
lastmod: "2012-07-23T22:38:33Z"
id: 1604690
url: "https://ansn001.iteye.com/blog/1604690"
---

FreeMarker是一个模板引擎，一个基于模板生成文本输出的通用工具，使用纯Java编写，  
模板用servlet提供的数据动态地生成 HTML，模板语言是强大的直观的，编译器速度快，  
输出接近静态HTML页面的速度。

 

**一．Freemarker模板应用事例。**  
1.创建模板文件，在/resource/template目录下建立freemarkerLocal.ftl文件。

Java代码  [![收藏代码](http://clq9761.iteye.com/images/icon_star.png)](http://clq9761.iteye.com/blog/1341534 "收藏这段代码")

01. ------------------普通变量获取-------------------
02. ${user}
03. ---------获取Map中属性--------------
04. ${latestProduct.url}
05. ${latestProduct.name}
06. -------自定义的indexOf方法变量-------
07. &lt;#assign x = "something"&gt;
08. ${indexOf("met", x)}
09. ${indexOf("foo", x)}
10. ------自定义的转换器变量(转换小写为大写,以标签形式展现)----------------
11. blah1
12. &lt;@upperCase&gt;
13. blah2
14. blah3
15. &lt;/@upperCase&gt;
16. blah4
17. ---------------共享变量的获取,在Configuration中设置---------------
18. &lt;@to\_upper&gt;
19. ${company}
20. &lt;/@to\_upper&gt;

 

2.代码解析模板文件输出。

Java代码  [![收藏代码](http://clq9761.iteye.com/images/icon_star.png)](http://clq9761.iteye.com/blog/1341534 "收藏这段代码")

01. public class FreemarkerLocalTest {
02. public static void main(String\[] args) throws Exception {
03. /* 一般在应用的整个生命周期中你仅需要执行一下代码一次\*/
04. /* 创建一个合适的configuration \*/
05. Configuration cfg = new Configuration();
06. // 设置模板加载的方式
07. cfg.setDirectoryForTemplateLoading(
08. new File("D:/myspace/freemarker/resource/template"));
09. // 方式二（从Web上下文获取)
10. // void setServletContextForTemplateLoading(Object servletContext, String path);
11. // 设置模板共享变量，所有的模板都可以访问设置的共享变量
12. cfg.setSharedVariable("to\_upper", new UpperCaseTransform());
13. cfg.setSharedVariable("company","FooInc.");
14. // 指定模板如何查看数据模型
15. cfg.setObjectWrapper(new DefaultObjectWrapper());
16. // 如果从多个位置加载模板，可采用以下方式
17. /\**
18. FileTemplateLoader ftl1 = new FileTemplateLoader(new File("/tmp/templates"));
19. FileTemplateLoader ftl2 = new FileTemplateLoader(new File("/usr/data/templates"));
20. ClassTemplateLoader ctl = new ClassTemplateLoader(getClass(),"");
21. TemplateLoader\[] loaders = new TemplateLoader\[] { ftl1, ftl2,ctl };
22. MultiTemplateLoader mtl = new MultiTemplateLoader(loaders);
23. cfg.setTemplateLoader(mtl);\*\*/
24. /* 而以下代码你通常会在一个应用生命周期中执行多次\*/
25. /\*获取或创建一个模版\*/
26. Template temp = cfg.getTemplate("freemarkerLocal.ftl");
27. /\*创建一个数据模型Create a data model \*/
28. Map root = new HashMap();
29. root.put("user", "Big Joe");
30. Map latest = new HashMap();
31. root.put("latestProduct", latest);
32. latest.put("url", "products/greenmouse.html");
33. latest.put("name", "green mouse");
34. // 方法变量，indexOf为自己定义的方法变量
35. root.put("indexOf", new IndexOfMethod());
36. // 转换器变量
37. root.put("upperCase", new UpperCaseTransform());
38. /* 合并数据模型和模版\*/
39. Writer out = new OutputStreamWriter(System.out);
40. temp.process(root, out);
41. out.flush();
42. }
43. }

 

3.自定义的方法变量类IndexOfMethod

Java代码  [![收藏代码](http://clq9761.iteye.com/images/icon_star.png)](http://clq9761.iteye.com/blog/1341534 "收藏这段代码")

01. public class IndexOfMethod implements TemplateMethodModel {
02. public Object exec(List args) throws TemplateModelException {
03. if (args.size() != 2) {
04. throw new TemplateModelException("Wrong arguments");
05. }
06. // 返回第一个字符串首次出现在第二个字符串的位置
07. return new SimpleNumber(((String) args.get(1))
08. .indexOf((String) args.get(0)));
09. }
10. }

 

4.自定义的转换器变量类UpperCaseTransform

Java代码  [![收藏代码](http://clq9761.iteye.com/images/icon_star.png)](http://clq9761.iteye.com/blog/1341534 "收藏这段代码")

01. /\**
02. * 转换器变量，自定义自己的转换器标签
03. \*/
04. import freemarker.template.TemplateTransformModel;
05. public class UpperCaseTransform implements TemplateTransformModel {
06. // 转换器接口方法，将会转换标签之间的内容，首先把标签之间的内容读取到Writer对象中，
07. // 再由Writer对象对其中的内容施行转换处理，转换后的内容会再次存储到Writer 中
08. public Writer getWriter(Writer out, Map args) {
09. return new UpperCaseWriter(out);
10. }
11. private class UpperCaseWriter extends Writer {
12. private Writer out;
13. UpperCaseWriter(Writer out) {
14. this.out = out;
15. }
16. public void write(char\[] cbuf, int off, int len) throws IOException {
17. out.write(new String(cbuf, off, len).toUpperCase());
18. }
19. public void flush() throws IOException {
20. out.flush();
21. }
22. // 不用调用out.close,到达结束标签close会自动被调用
23. public void close() {
24. }
25. }
26. }

 

**二．自动生成代码应用**

1.创建模板文件，在/resource/template目录下建立codeModel.ftl文件。

Java代码  [![收藏代码](http://clq9761.iteye.com/images/icon_star.png)](http://clq9761.iteye.com/blog/1341534 "收藏这段代码")

01. package com.order.model;
02. public class ${class} {
03. &lt;#list properties as prop&gt;
04. private ${prop.type} ${prop.name};
05. &lt;/#list&gt;
06. &lt;#list properties as prop&gt;
07. public ${prop.type} get${prop.name?cap\_first}(){
08. return ${prop.name};
09. }
10. public void set${prop.name?cap\_first}(${prop.type} ${prop.name}){
11. this.${prop.name} = ${prop.name};
12. }
13. &lt;/#list&gt;
14. }

 

2.应用代码生成模板文件。

Java代码  [![收藏代码](http://clq9761.iteye.com/images/icon_star.png)](http://clq9761.iteye.com/blog/1341534 "收藏这段代码")

01. public class GenerateCodeTest {
02. public static void main(String args\[]) throws IOException,
03. TemplateException {
04. Configuration cfg = new Configuration();
05. cfg.setDirectoryForTemplateLoading(new File(
06. "D:/myspace/freemarker/resource/template/"));
07. cfg.setObjectWrapper(new DefaultObjectWrapper());
08. /* 获取模板文件 \*/
09. Template template = cfg.getTemplate("codeModel.ftl");
10. /* 模板数据 \*/
11. Map&lt;String, Object&gt; root = new HashMap&lt;String, Object&gt;();
12. root.put("class", "Order");
13. Collection&lt;Map&lt;String, String&gt;&gt; properties = new HashSet&lt;Map&lt;String, String&gt;&gt;();
14. root.put("properties", properties);
15. /* 字段1 orderId \*/
16. Map&lt;String, String&gt; orderId = new HashMap&lt;String, String&gt;();
17. orderId.put("name", "orderId");
18. orderId.put("type", "Long");
19. properties.add(orderId);
20. /* 字段2 orderName \*/
21. Map&lt;String, String&gt; orderName = new HashMap&lt;String, String&gt;();
22. orderName.put("name", "orderName");
23. orderName.put("type", "String");
24. properties.add(orderName);
25. /* 字段3 money \*/
26. Map&lt;String, String&gt; money = new HashMap&lt;String, String&gt;();
27. money.put("name", "money");
28. money.put("type", "Double");
29. properties.add(money);
30. /* 生成输出到控制台 \*/
31. Writer out = new OutputStreamWriter(System.out);
32. template.process(root, out);
33. out.flush();
34. /* 生成输出到文件 \*/
35. File fileDir = new File("D:/generateCodeFile");
36. // 创建文件夹，不存在则创建
37. org.apache.commons.io.FileUtils.forceMkdir(fileDir);
38. // 指定生成输出的文件
39. File output = new File(fileDir + "/Order.java");
40. Writer writer = new FileWriter(output);
41. template.process(root, writer);
42. writer.close();
43. }
44. }

 **三．JSP调用模板文件输出。**

1.首先创建模板文件，在WEB-INF/templates目录下建立test.ftl文件。

Java代码  [![收藏代码](http://clq9761.iteye.com/images/icon_star.png)](http://clq9761.iteye.com/blog/1341534 "收藏这段代码")

1. Hello,${name}!

2.解析模板文件类，传入pageContext参数。

Java代码  [![收藏代码](http://clq9761.iteye.com/images/icon_star.png)](http://clq9761.iteye.com/blog/1341534 "收藏这段代码")

01. public class FreemarkerTest {
02. public void execute(PageContext pageContext) throws Exception
03. {
04. Configuration cfg = new Configuration();
05. // 设置模板的路径
06. cfg.setServletContextForTemplateLoading(pageContext.getServletContext(),
07. "WEB-INF/templates");
08. Map root = new HashMap();
09. root.put("name", "Tom");
10. // 获取模板文件
11. Template t = cfg.getTemplate("test.ftl");
12. Writer out = pageContext.getResponse().getWriter();
13. t.process(root, out);
14. }
15. }

 3.创建JSP文件调用输出。

Html代码  [![收藏代码](http://clq9761.iteye.com/images/icon_star.png)](http://clq9761.iteye.com/blog/1341534 "收藏这段代码")

01. &lt;%@ page language="java" contentType="text/html; charset=GB2312"
02. pageEncoding="GB2312"%&gt;
03. &lt;%@page import="com.freemarker.test.FreemarkerTest;"%&gt;
04. &lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
05. "http://www.w3.org/TR/html4/loose.dtd"&gt;
06. &lt;html&gt;
07. &lt;head&gt;
08. &lt;meta http-equiv="Content-Type" content="text/html; charset=GB2312"&gt;
09. &lt;title&gt;HelloWorld&lt;/title&gt;
10. &lt;/head&gt;
11. &lt;body&gt;
12. &lt;%
13. FreemarkerTest c1 = new FreemarkerTest();
14. c1.execute(pageContext);
15. %&gt;
16. &lt;/body&gt;
17. &lt;/html&gt;

 **四．Servlet调用模板文件生成html文件进行页面展示。**

1.创建模板文件，在WebRoot/index目录下建立test.ftl文件。 

Java代码  [![收藏代码](http://clq9761.iteye.com/images/icon_star.png)](http://clq9761.iteye.com/blog/1341534 "收藏这段代码")

1. &lt;html&gt;
2. &lt;body&gt;
3. 用户名:${userName}&lt;br&gt;
4. 邮&nbsp;&nbsp;箱:${email}
5. &lt;/body&gt;
6. &lt;/html&gt;

 

2.创建Servlet文件解析模板文件并生成html文件进行页面输出。

Java代码  [![收藏代码](http://clq9761.iteye.com/images/icon_star.png)](http://clq9761.iteye.com/blog/1341534 "收藏这段代码")

01. public class FreemarkerServletTest extends HttpServlet {
02. public FreemarkerServletTest() {
03. super();
04. }
05. public void destroy() {
06. super.destroy();
07. }
08. public void doGet(HttpServletRequest request, HttpServletResponse response)
09. throws ServletException, IOException {
10. doPost(request, response);
11. }
12. public void doPost(HttpServletRequest request, HttpServletResponse response)
13. throws ServletException, IOException {
14. //生成html后的文件
15. String path = getServletContext().getRealPath("/") + "index.htm";
16. System.out.println(path);
17. try {
18. freemarker(request, "test.ftl", path, "index");
19. } catch (Exception e) {
20. e.printStackTrace();
21. }
22. //跳转到刚生成的html文件中
23. request.getRequestDispatcher("/index.htm").forward(request, response);
24. }
25. /\**
26. * 生成静态文件
27. * @param request
28. * @param ftl ftl文件
29. * @param html 生成html后的文件
30. * @param file 存放ftl文件的路径
31. * @throws Exception
32. \*/
33. public void freemarker(HttpServletRequest request,String ftl,
34. String html,String file) throws Exception {
35. Configuration cfg = new Configuration();
36. // 设置加载模板的路径
37. cfg.setServletContextForTemplateLoading(getServletContext(),"/" + file);
38. cfg.setEncoding(Locale.getDefault(), "GB18030");
39. //获得模板并设置编码
40. Template tep = cfg.getTemplate(ftl);
41. tep.setEncoding("GB18303");
42. //新建输出，生成html文件
43. Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(html),"GB18030"));
44. //设置值
45. Map map = new HashMap();
46. map.put("userName", "wxj");
47. map.put("email", "jxauwxj@126.com");
48. // 解析并输出
49. tep.process(map, out);
50. }
51. public void init() throws ServletException {
52. }
53. }

 

3.web.xml文件进行servlet配置。

Xml代码  [![收藏代码](http://clq9761.iteye.com/images/icon_star.png)](http://clq9761.iteye.com/blog/1341534 "收藏这段代码")

1. &lt;servlet&gt;
2. &lt;servlet-name&gt;FreemarkerServletTest&lt;/servlet-name&gt;
3. &lt;servlet-class&gt;com.servlet.FreemarkerServletTest&lt;/servlet-class&gt;
4. &lt;/servlet&gt;
5. &lt;servlet-mapping&gt;
6. &lt;servlet-name&gt;FreemarkerServletTest&lt;/servlet-name&gt;
7. &lt;url-pattern&gt;/servlet/FreemarkerServletTest&lt;/url-pattern&gt;
8. &lt;/servlet-mapping&gt;

 

4.页面访问如下Url：  
  [http://localhost:8080/freemarkerWeb/servlet/FreemarkerServletTest](http://localhost:8080/freemarkerWeb/servlet/FreemarkerServletTest)     
输出结果如下：

Java代码  [![收藏代码](http://clq9761.iteye.com/images/icon_star.png)](http://clq9761.iteye.com/blog/1341534 "收藏这段代码")

1. 用户名:wxj
2. 邮  箱:jxauwxj@126.com

 

同时会在部署环境的目录下生成index.htm文件。