freemaker的初步使用(一)

本文介绍了一个Freemarker实用类的实现,包括获取模板、输出到控制台及文件的功能,并提供了一个简单的HTML模板示例。


1.编写freemaker实用类:

package org.konghao.freemarker;

import java.io.File;
import java.io.FileWriter;
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 {
	//getTemplate("01.ftl")
	public Template getTemplate(String name) {
		try {
			//通过Freemaker的Configuration读取相应的ftl
			Configuration cfg = new Configuration();
			//设定去哪里读取相应的ftl模板文件
			cfg.setClassForTemplateLoading(this.getClass(),"/ftl");
			//在模板文件目录中找到名称为name的文件
			Template temp = cfg.getTemplate(name);
			return temp;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void print(String name,Map<String,Object> root) {
		try {
			//通过Template可以将模板文件输出到相应的流
			Template temp = this.getTemplate(name);
			temp.process(root, new PrintWriter(System.out));
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void fprint(String name,Map<String,Object> root,String outFile) {
		FileWriter out = null;
		try {
			//通过一个文件输出流,就可以写到相应的文件中
			out = new FileWriter(new File("D:\\webservice\\ftl\\"+outFile));
			Template temp = this.getTemplate(name);
			temp.process(root, out);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		} finally {
			try {
				if(out!=null) out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}

2.编写模板文件

<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>

3.目录结构:


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值