Let`s drink code
这是我们自定义的工具类FreeMarkerUtil.java
package com.jadyer.util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class FreeMarkerUtil {
/**
* 获取指定目录下的模板文件
* @param name 模板文件的名称
* @param pathPrefix 模板文件的目录
*/
public Template getTemplate(String name, String pathPrefix) throws IOException{
Configuration cfg = new Configuration(); //通过FreeMarker的Configuration对象可以读取ftl文件
cfg.setClassForTemplateLoading(this.getClass(), pathPrefix); //设置模板文件的目录
cfg.setDefaultEncoding("UTF-8"); //Set the default charset of the template files
Template temp = cfg.getTemplate(name); //在模板文件目录中寻找名为"name"的模板文件
return temp; //此时FreeMarker就会到类路径下的"pathPrefix"文件夹中寻找名为"name"的模板文件
}
/**
* 根据模板文件输出内容到控制台
* @param name 模板文件的名称
* @param pathPrefix 模板文件的目录
* @param rootMap 模板的数据模型
*/
public void print(String name, String pathPrefix, Map rootMap) throws TemplateException, IOException{
this.getTemplate(name, pathPrefix).process(rootMap, new PrintWriter(System.out));
}
/**
* 根据模板文件输出内容到指定的文件中
* @param name 模板文件的名称
* @param pathPrefix 模板文件的目录
* @param rootMap 模板的数据模型
* @param file 内容的输出文件
*/
public void printFile(String name, String pathPrefix, Map rootMap, File file) throws TemplateException, IOException{
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
this.getTemplate(name, pathPrefix).process(rootMap, out); //将模板文件内容以UTF-8编码输出到相应的流中
if(null != out){
out.close();
}
}
}
这是位于//src//ftl//包中用于演示分页效果的paginUsage.ftl
分页效果:
这是位于//src//ftl//inc//包中用于生成分页的通用指令的pagin.ftl
自定义指令genPagin的参数说明,如下
url 必填。用于指定链接所跳转的URL
totalPages 必填。用于指定总页数
currPage 选填。用于指定当前显示第几页,默认显示第一页
showPageNum 选填。用于指定所显示页链接的数量,默认显示10个页链接。否则总不能把所有页的链接都显示出来吧
class 选填。用于指定的class属性
-->
=currPage)>
totalPages)>
#if>
#if>
#macro>
[${page}]
#if>
#list>
#macro>
最后是JUnit4.x编写的单元测试类FreeMarkerTest.java
package com.jadyer.test;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import org.junit.Test;
import com.jadyer.util.FreeMarkerUtil;
import freemarker.template.TemplateException;
public class FreeMarkerTest {
@Test
public void print() throws TemplateException, IOException{
new FreeMarkerUtil().print("paginUsage.ftl", "/ftl", new HashMap());
new FreeMarkerUtil().printFile("paginUsage.ftl", "/ftl", new HashMap(), new File("D:\\ftl\\my.html"));
}
}