FreeMarker学习使用(1)

FreeMarker的使用比较简单,只需要一个FreeMarker的jar包即可。
1.新建一个java project,命名为:FreemarkerTest。
2.导入jar包:
freemarker.jar
junit-4.10.jar
3.新建一个文件夹,命名templates,在该目录下新建两个模板,01.ftl和02.ftl:
01.ftl:
你好:${username}
02.ftl:
<html>
  <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>Insert title here</title>
  </head>
  <body>
      <h1>${username}</h1>
  </body>
</html>
4.编写一个FreeMarker的工具类:
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Map;

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

public class FreemarkerUtil {
	// 负责管理FreeMarker模板的Configuration实例
	private Configuration cfg = null;
	
	/**
	 * 获取freemarker模板
	 * @param filename 文件名
	 * @return 返回freemarker模板
	 */
	public Template getTemplate(String filename) {
		try {
			cfg = new Configuration();
			// 指定FreeMarker模板文件的位置  
			String filepath = System.getProperty("user.dir");
			cfg.setDirectoryForTemplateLoading(new File(filepath+"/templates"));
			//获取模板文件
			Template template = cfg.getTemplate(filename);
			return template;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}
	
	/**
	 * 输出到控制台
	 * @param filename 模板文件名
	 * @param root 数据模型
	 */
	public void print(String filename,Map root) {
		try {
			Template template = getTemplate(filename);
			template.process(root, new PrintWriter(System.out));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 输出到文件
	 * @param filename 模板文件名
	 * @param root 数据模型
	 * @param outFilename 输出的文件名
	 */
	public void printf(String filename,Map<String,String> root,String outFilename) {
		try {
			Template template = getTemplate(filename);
			FileWriter fw = new FileWriter(new File("d:/" + outFilename));
			template.process(root, fw);
			fw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
4.新建一个测试类:
public class FreemarkerTest {
	FreemarkerUtil fu = null;
	Map<String,String> root = null;
	@Before
	public void init() {
		fu = new FreemarkerUtil();
		root = getHashMapInstance();
	}
	
	@Test
	public void testPrint() {
		root.put("username", "abc");
		fu.print("01.ftl", root);
		fu.print("02.ftl", root);
	}
	
	@Test
	public void getPath() {
		File f = new File(this.getClass().getResource("/").getPath()); 
		System.out.println(f); 
		System.out.println(System.getProperty("user.dir")); 
	}
	
	public <K,V>Map getHashMapInstance() {
		return new HashMap<K,V>();
	}
}

总结:
1.用了2个模板只是为了说明FreeMarker无论什么格式的文件都能处理,其实就是把${}部分替换成Map里相同key的value。

代码地址:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值