您的位置:首页 > 其它

freemarker入门小例子

2014-08-18 13:43 246 查看
在项目中有一些只有部分变动的数据使用模板技术能达到很好的效果,其重用性大大提高。笔者今天讲的是freemaker的一个使用。

1. 引入freemarkerjar包

<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.20</version>
</dependency>


2. 创建工具类

  

public class FreeMarkerUtil {
static Configuration cfg;
Template template;

static {
try {
getConfiguration();
} catch (IOException e) {
e.printStackTrace();
}
}

private static void getConfiguration() throws IOException {
cfg = new Configuration();
// classpath下
String path = Thread.currentThread().getContextClassLoader()
.getResource("./").getPath();
File templateDirFile = new File(path);
cfg.setDirectoryForTemplateLoading(templateDirFile);
cfg.setDefaultEncoding("UTF-8");
}

// 获取处理后的模板数据
public String getProcessedTemplateData(String templateName,
Map<String, Object> params) {
try {
template = cfg.getTemplate(templateName);
StringWriter result = new StringWriter();
template.process(params, result);
return result.toString();

} catch (Exception e) {
e.printStackTrace();
return null;
}
}

// 生成文件
public boolean generateFile(String templateName, Map<String, Object> params) {
try {
template = cfg.getTemplate(templateName);
FileUtils.forceMkdir(new File("D:\\"));
OutputStreamWriter out = new OutputStreamWriter(
new FileOutputStream("D:\\xxx.html"),
"UTF-8");
template.process(params, out);
out.close();
} catch (Exception e) {
return false;
}
return true;
}
}


两种方式操作,方便简单。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: