ITeye博客

Freemarker模板应用

ansn001 · 2012-07-23 22:38 · Architecture · 编程语言 · ftl · Markdown

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

 

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

Java代码  收藏代码

  1. ------------------普通变量获取-------------------
  2. ${user}
  3. ---------获取Map中属性--------------
  4. ${latestProduct.url}
  5. ${latestProduct.name}
  6. -------自定义的indexOf方法变量-------
  7. <#assign x = "something">
  8. ${indexOf("met", x)}
  9. ${indexOf("foo", x)}
  10. ------自定义的转换器变量(转换小写为大写,以标签形式展现)----------------
  11. blah1
  12. <@upperCase>
  13. blah2
  14. blah3
  15. </@upperCase>
  16. blah4
  17. ---------------共享变量的获取,在Configuration中设置---------------
  18. <@to_upper>
  19. ${company}
  20. </@to_upper>

 

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

Java代码  收藏代码

  1. public class FreemarkerLocalTest {
  2. public static void main(String[] args) throws Exception {
  3. /* 一般在应用的整个生命周期中你仅需要执行一下代码一次*/
  4. /* 创建一个合适的configuration */
  5. Configuration cfg = new Configuration();
  6. // 设置模板加载的方式
  7. cfg.setDirectoryForTemplateLoading(
  8. new File("D:/myspace/freemarker/resource/template"));
  9. // 方式二(从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代码  收藏代码

  1. public class IndexOfMethod implements TemplateMethodModel {
  2. public Object exec(List args) throws TemplateModelException {
  3. if (args.size() != 2) {
  4. throw new TemplateModelException("Wrong arguments");
  5. }
  6. // 返回第一个字符串首次出现在第二个字符串的位置
  7. return new SimpleNumber(((String) args.get(1))
  8. .indexOf((String) args.get(0)));
  9. }
  10. }

 

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

Java代码  收藏代码

  1. /**
  2. * 转换器变量,自定义自己的转换器标签
  3. */
  4. import freemarker.template.TemplateTransformModel;
  5. public class UpperCaseTransform implements TemplateTransformModel {
  6. // 转换器接口方法,将会转换标签之间的内容,首先把标签之间的内容读取到Writer对象中,
  7. // 再由Writer对象对其中的内容施行转换处理,转换后的内容会再次存储到Writer 中
  8. public Writer getWriter(Writer out, Map args) {
  9. 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代码  收藏代码

  1. package com.order.model;
  2. public class ${class} {
  3. <#list properties as prop>
  4. private ${prop.type} ${prop.name};
  5. </#list>
  6. <#list properties as prop>
  7. public ${prop.type} get${prop.name?cap_first}(){
  8. return ${prop.name};
  9. }
  10. public void set${prop.name?cap_first}(${prop.type} ${prop.name}){
  11. this.${prop.name} = ${prop.name};
  12. }
  13. </#list>
  14. }

 

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

Java代码  收藏代码

  1. public class GenerateCodeTest {
  2. public static void main(String args[]) throws IOException,
  3. TemplateException {
  4. Configuration cfg = new Configuration();
  5. cfg.setDirectoryForTemplateLoading(new File(
  6. "D:/myspace/freemarker/resource/template/"));
  7. cfg.setObjectWrapper(new DefaultObjectWrapper());
  8. /* 获取模板文件 */
  9. Template template = cfg.getTemplate("codeModel.ftl");
  10. /* 模板数据 */
  11. Map<String, Object> root = new HashMap<String, Object>();
  12. root.put("class", "Order");
  13. Collection<Map<String, String>> properties = new HashSet<Map<String, String>>();
  14. root.put("properties", properties);
  15. /* 字段1 orderId */
  16. Map<String, String> orderId = new HashMap<String, String>();
  17. orderId.put("name", "orderId");
  18. orderId.put("type", "Long");
  19. properties.add(orderId);
  20. /* 字段2 orderName */
  21. Map<String, String> orderName = new HashMap<String, String>();
  22. orderName.put("name", "orderName");
  23. orderName.put("type", "String");
  24. properties.add(orderName);
  25. /* 字段3 money */
  26. Map<String, String> money = new HashMap<String, String>();
  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代码  收藏代码

  1. Hello,${name}!

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

Java代码  收藏代码

  1. public class FreemarkerTest {
  2. public void execute(PageContext pageContext) throws Exception
  3. {
  4. Configuration cfg = new Configuration();
  5. // 设置模板的路径
  6. cfg.setServletContextForTemplateLoading(pageContext.getServletContext(),
  7. "WEB-INF/templates");
  8. Map root = new HashMap();
  9. 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代码  收藏代码

  1. <%@ page language="java" contentType="text/html; charset=GB2312"
  2. pageEncoding="GB2312"%>
  3. <%@page import="com.freemarker.test.FreemarkerTest;"%>
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  5. "http://www.w3.org/TR/html4/loose.dtd">
  6. <html>
  7. <head>
  8. <meta http-equiv="Content-Type" content="text/html; charset=GB2312">
  9. <title>HelloWorld</title>
  10. </head>
  11. <body>
  12. <%
  13. FreemarkerTest c1 = new FreemarkerTest();
  14. c1.execute(pageContext);
  15. %>
  16. </body>
  17. </html>

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

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

Java代码  收藏代码

  1. <html>
  2. <body>
  3. 用户名:${userName}<br>
  4. 邮  箱:${email}
  5. </body>
  6. </html>

 

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

Java代码  收藏代码

  1. public class FreemarkerServletTest extends HttpServlet {
  2. public FreemarkerServletTest() {
  3. super();
  4. }
  5. public void destroy() {
  6. super.destroy();
  7. }
  8. public void doGet(HttpServletRequest request, HttpServletResponse response)
  9. 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代码  收藏代码

  1. <servlet>
  2. <servlet-name>FreemarkerServletTest</servlet-name>
  3. <servlet-class>com.servlet.FreemarkerServletTest</servlet-class>
  4. </servlet>
  5. <servlet-mapping>
  6. <servlet-name>FreemarkerServletTest</servlet-name>
  7. <url-pattern>/servlet/FreemarkerServletTest</url-pattern>
  8. </servlet-mapping>

 

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

Java代码  收藏代码

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

 

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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。