设为首页 加入收藏

TOP

freemaker的初步使用
2014-11-24 12:02:18 来源: 作者: 【 】 浏览:36
Tags:freemaker 初步 使用
1.编写freemaker实用类:
[java]
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 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 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]
Insert title here

${username}

3.目录结构:
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇注解方式---spring的AOP拦截用户.. 下一篇FreeMarker教程

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: