TemplateUtils.java
2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package com.cjs.cms.util.file;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import com.cjs.cms.util.net.RestException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
/**
* FreeMarker模板工具类
*
* @author trunks
* @version $Id: TemplateUtils.java, v 0.1 2012-3-7 下午03:25:08 trunks Exp $
*/
public class TemplateUtils {
private Map<String, Object> result = new HashMap<String, Object>();
public TemplateUtils() {
}
/**
* 添加要在模板显示的数据
*/
public void put(String key, Object value) {
result.put(key, value);
}
/**
* 生成静态文件
*
* @param tpl 模板文件名
* @param target 生成文件目标路径
*/
public void createHtml(String tpl, String target) {
ConfigurationInstance cfg = ConfigurationInstance.getInstance();
BufferedWriter writer = null;
try {
File file = new File(target.substring(0, target.lastIndexOf("/")));
if (!file.exists()) {
file.mkdirs();
}
Template template = cfg.getTemplate(tpl);
writer = new BufferedWriter(new FileWriter(target));
template.process(result, writer);
writer.flush();
} catch (IOException e) {
throw new RestException("生成静态文件出错:" + e.getMessage());
} catch (TemplateException e) {
throw new RestException("生成静态文件出错:" + e.getMessage());
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
}
}
}
}
/**
* 读取处理后的模板内容
*
* @param tpl 模板名
* @return 处理后的模板内容
*/
public String readProcessedTemplate(String tpl) {
StringWriter writer = new StringWriter();
try {
ConfigurationInstance cfg = ConfigurationInstance.getInstance();
Template template = cfg.getTemplate(tpl);
template.process(result, writer);
} catch (IOException e) {
throw new RestException("读取模板文件出错:" + e.getMessage());
} catch (TemplateException e) {
throw new RestException("读取模板文件出错:" + e.getMessage());
}
return writer.toString();
}
public Map<String, Object> getResult() {
return result;
}
public void setResult(Map<String, Object> result) {
this.result = result;
}
}