这里有个系列博客很不错,应该是最合适的入门教程了。Java模板引擎FreeMarker系列
这里的对FreeMarker的简介也很棒:使用Java对FreeMarker开发Web模板html
FreeMarker是一个模板引擎,一个基于模板生成文本输出的通用工具,使用纯Java编写,被主要用来生成HTML页面,特别是基于MVC模式的Web应用的页面。固然,FreeMarker一样能够应用于非Web应用程序环境。虽然FreeMarker具备一些编程的能力,但一般由Java程序准备要显示的数据,由FreeMarker模板显示准备的数据(以下图)java
FreeMarker不是一个Web应用框架,也与容器无关,由于它并不知道HTTP或者Servlet。它适合做为Model2框架(如Struts)的视图组件。FreeMarker模板也支持JSP标签库。编程
Freemarker生成静态页面的过程是,模板引擎读取模板页面,解析其中的标签,完成指令相对应的操做,而后采用键值对的方式传递参数替换模板中的取值表达式,最后根据配置的路径生成一个新的静态页面。app
${…}
:取值标签。表示输出变量的内容。如:${name}
能够取得root中key为name的值。${person.name}
能够取得成员变量为person的name属性。框架
<#…>
:FTL指令(FreeMarker模板语言标记)如:<#if>
表示判断、<#list>
表示循环枚举、<#include>
表示包含其余页面。函数
<@…>
:宏,自定义标签。工具
注释:包含在<#--
和-->
之间。学习
模板 + 数据模型 = 输出ui
英文就是 template + data-model = outputthis
首先,建立模板以下:
<html> <head> <title>Welcome!</title> </head> <body> <h1>Welcome ${user}!</h1> <p>Our latest product: <a href="${latestProduct.url}">${latestProduct.name}</a>! </body> </html>
在程序端,只须要简单的四步:
获得Configuration类的实例。
建立data-model对象。
获取template文件。
把template和data-model捏合到一块儿产生输出。
代码以下:
首先建立data-model类:
/** * Product bean; note that it must be a public class! */ public class Product { private String url; private String name; // As per the JavaBeans spec., this defines the "url" bean property // It must be public! public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } // As per the JavaBean spec., this defines the "name" bean property // It must be public! public String getName() { return name; } public void setName(String name) { this.name = name; } }
主函数:
import freemarker.template.*; import java.util.*; import java.io.*; public class Test { public static void main(String[] args) throws Exception { /* ------------------------------------------------------------------------ */ /* You should do this ONLY ONCE in the whole application life-cycle: */ /* Create and adjust the configuration singleton */ Configuration cfg = new Configuration(Configuration.VERSION_2_3_25); cfg.setDirectoryForTemplateLoading(new File("/where/you/store/templates")); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); cfg.setLogTemplateExceptions(false); /* ------------------------------------------------------------------------ */ /* You usually do these for MULTIPLE TIMES in the application life-cycle: */ /* Create a data-model */ Map root = new HashMap(); root.put("user", "Big Joe"); Product latest = new Product(); latest.setUrl("products/greenmouse.html"); latest.setName("green mouse"); root.put("latestProduct", latest); /* Get the template (uses cache internally) */ Template temp = cfg.getTemplate("test.ftlh"); /* Merge data-model with template */ Writer out = new OutputStreamWriter(System.out); temp.process(root, out); // Note: Depending on what `out` is, you may need to call `out.close()`. // This is usually the case for file output, but not for servlet output. } }
能够看到,有了JSP的知识,FreeMarker仍是很好学习的。更多的用法能够参考上面的博客以及官方教程。本篇到此为止。