Freemarker生成静态文件

Freemarker是一个比较知名Java模版引擎,使用人数众多,今天记录下使用Freemarker来生成静态文件,主要应用场景为页面静态化以及代码生成器中。

引入Maven依赖

目前最新的版本

1
2
3
4
5
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.26-incubating</version>
</dependency>

开始编码

新建一个工具类,比如FreemarkerUtils,具体代码如下:

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
private static Configuration cfg = null;
/**
* 获取Configuration对象
*/
private Configuration getConfiguration() {
if (null == cfg) {
cfg = new Configuration(Configuration.VERSION_2_3_26);
//设置模版放置路径,这里表示在classpath下的templates文件夹下
cfg.setClassForTemplateLoading(this.getClass(), "/templates/");
// 设置编码
cfg.setEncoding(Locale.getDefault(), "UTF-8");
// 设置对象的包装器
cfg.setObjectWrapper(new DefaultObjectWrapper());
// 设置异常处理器,否则没有的属性将会报错
cfg.setTemplateExceptionHandler(TemplateExceptionHandler
.IGNORE_HANDLER);
}
return cfg;
}

/**
* 生成静态文件
* @param templatePath 模版路径
* @param data 模版需要的数据
* @param outputPath 输出路径
* @return
*/
public boolean createFile(String templatePath, Map<String, Object> data,
String outputPath) {
try {
// 获取Freemarker的Configuration
Configuration cfg = getConfiguration();
// 创建Template对象
Template template = cfg.getTemplate(templatePath);
// 生成静态页面
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputPath), "UTF-8"));
template.process(data, out);
out.flush();
out.close();
} catch (IOException | TemplateException e) {
return false;
}
return true;
}

在maven项目resources下创建templates文件夹,用于存放模版文件,然后新建一个test.ftl模版文件,即可根据这个文件来进行定制生成我们想要的静态文件。

测试

1
2
3
4
FreemarkerUtils f = new FreemarkerUtils ();
Map<String,Object> data = new HashMap<>();
data.put("name","hello world");
f.createFile("test.ftl",data,"D:\\test.ftl");

直接运行即可,就会看到D盘下生成我们需要的静态文件了。

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×