FreeMarker新手指南第一册

什么是freemarker

FreeMarker是一个用Java语言编写的模板引擎,它基于模板来生成文本输出。
FreeMarker与Web容器无关,即在Web运行时,它并不知道Servlet或HTTP。它不仅可以用作表现层的实现技术,而且还可以用于生成XML,JSP或Java 等。

目前企业中:主要用Freemarker做静态页面或是页面展示

使用freemarker需要的jar
把下载到的jar包(freemarker-2.3.23.jar)放到\WebRoot\WEB-INF\lib目录下。
官方网站:http://freemarker.org/

如果使用的是Maven结构,可在pom.xml中引入以下坐标

Freemarker原理图

模板 +  数据模型 = 输出

应用例子

测试类 FMDemo

String dir = "C:\\Users\\lx\\workspace-e\\freemarker-java\\";
Configuration conf = new Configuration(Configuration.VERSION_2_3_23);
//加载模板文件(模板的路径)
conf.setDirectoryForTemplateLoading(new File(dir));
//配置默认字符集
configuration.setDefaultEncoding("utf-8");
// 加载模板
Template template = conf.getTemplate("ftl/freemarker-demo.ftl");
// 定义数据
Map root = new HashMap();
root.put("world", "世界你好");
// 定义输出
Writer out = new FileWriter(dir + "ftl/freemarker.html");
template.process(root, out);
out.flush();
out.close();
页面
${world}

访问对象

Person p  = new Person();
Map root = new HashMap();
root.put(“person”,p);

freemarker.html内容如下:
${person.id}=${person.name}


历遍集合/数组

List<Person> persons = new ArrayList<Person>();
省略….

页面中内容

<#list persons as p>
${p.id}/${p.name}
</#list>

获得当前迭代的索引

List<Person> list = new ArrayList<Person>();

获取当前选代的索引:<br/>
<#list persons as p>
${p_index}
</#list>

#if

逻辑运算符(==   !=   ||   &&)

<html>
<body>
<#list persons as p>
<#if p_index%2 != 0 || p_index==0>
输出一行字
</#if>
index:${p_index}|${p.id}:${p.name}<br>
</#list>
</body>
</html>

#else

<html>
<body>
<#list persons as p>
<#if p_index%2 != 0 || p_index==0>
<span style="color:red">
index:${p_index}|${p.id}:${p.name}<br>
</span>
<#else>
<span style="color:blue">
index:${p_index}|${p.id}:${p.name}<br>
</span>
</#if>
</#list>
</body>


格式化日期

默认格式
1:date
${cur_time?date}
2:datetime
${cur_time?datetime}
3:time
${cur_time?time}

自定义格式
${cur_time?string("yyyy-MM-dd HH:mm:ss")}  

null处理

root.put(“val”,null);


解决办法
1:null 变 空串
${val!}     ${val!"这里是空"}
2:为Null时给默认值
${val!“我是默认值"}
3:
<#if curdate ??>
属性不为空
<#else>
属性为空
<#/if>

include

将另一个页面引入本页面时可用以下命令完成


<#include "/include/head.html">


freemaker整合spring

添加依赖:



在ApplicationContext.xml中添加如下内容:



代码中使用:

Configuration configuration = freeMarkerConfigurer.getConfiguration(); Template template = configuration.getTemplate("item.ftl"); Map root = new HashMap(); //取商品信息 .... FileWriter out = new FileWriter(new File(HTML_GEN_PATH + id + ".html")); template.process(root, out); out.flush(); out.close();