freemarker入门实例(二)FreemarkerUtil

package com.lj.freemarker;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreemarkerUtil
{
	private static FreemarkerUtil util;
	private static Configuration cfg;
	
	private FreemarkerUtil(){
		
	}
	
	/**
	 * 获取单例对象
	 * @param pname ftl模板文件所在路径
	 * @return
	 */
	public static FreemarkerUtil getInstance(String pname){
		if(util==null){
			 cfg=new Configuration();
			 cfg.setClassForTemplateLoading(FreemarkerUtil.class, pname);
			util=new FreemarkerUtil();
		}
		return util;
	}
	
	
	/**
	 * 获取模板对象
	 * @param fname 模板文件名称
	 * @return
	 */
	private Template getTemplate(String fname){
		try
		{
			return cfg.getTemplate(fname);
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 通过标准输出流输出模板的结果
	 * @param root 数据对象
	 * @param fname 模板文件名
	 */
	public void sprint(Map<String,Object>root,String fname){
		try
		{
			getTemplate(fname).process(root, new PrintWriter(System.out));
		}
		catch (TemplateException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 基于文件输出
	 * @param root 数据对象
	 * @param fname 模板文件名
	 * @param outpath 输出文件路径
	 */
	public void fprint(Map<String,Object> root, String fname, String outpath){
		try
		{
			getTemplate(fname).process(root, new PrintWriter(new File(outpath)));
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (TemplateException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		
	}
	
	
	
}



测试代码:
package com.lj.freemarker;

import java.util.HashMap;
import java.util.Map;

import org.junit.Before;
import org.junit.Test;

public class TestFreemarkerUtil
{	
	private FreemarkerUtil util=FreemarkerUtil.getInstance("/ftl");
	private Map<String,Object> root=new HashMap<String,Object>();
	
	private String fn="d:/";
	
	@Before
	public void setUp(){
		root.put("username", "alleni");
	}
	
	@Test
	public void test01(){
		util.sprint(root, "hello.ftl");
		util.fprint(root, "hello.ftl", fn+"1.txt");
	}
}

猜你喜欢

转载自alleni123.iteye.com/blog/2008688