freemarker是类似于jsp的一种模板技术,开发者可以灵活地使用自定义模板,然后根据业务逻辑,将业务数据嵌入到模板当中,形成最终的业务数据展现板式。
首先,先定义一个名叫freeMakerTestTemplate.ftlh的模板文件:
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome ${user}!</h1>
<p>Our latest product:
<a href="${latestProduct.url}">${latestProduct.name}</a>!
</body>
</html>
然后定义一个业务对象,Product:
package com.zkm.freemarker;
/**
* Product bean; note that it must be a public class!
*/
public class Product {
private String url;
private String name;
// As per the JavaBeans spec., this defines the "url" bean property
// It must be public!
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
// As per the JavaBean spec., this defines the "name" bean property
// It must be public!
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
接下来,在主程序中,将业务数据和模板进行合并:
package com.zkm.freemarker;
import freemarker.template.*;
import java.util.*;
import java.io.*;
public class FreeMarkerTest {
// freemaker官方例子
public static void main(String[] args) throws Exception {
/* You should do this ONLY ONCE in the whole application life-cycle: */
/* Create and adjust the configuration singleton */
Configuration cfg = new Configuration(Configuration.VERSION_2_3_25);
cfg.setDirectoryForTemplateLoading(new File("./zkm-live/templates/freemarker"));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptions(false);
/*
* You usually do these for MULTIPLE TIMES in the application
* life-cycle:
*/
/* Create a data-model */
Map<String, Object> root = new HashMap<String, Object>();
root.put("user", "Big Joe");
Product latest = new Product();
latest.setUrl("products/greenmouse.html");
latest.setName("green mouse");
root.put("latestProduct", latest);
/* Get the template (uses cache internally) */
OutputStream out = null;
Writer writer = null;
try {
Template temp = cfg.getTemplate("freeMakerTestTemplate.ftlh");
/* Merge data-model with template */
out = new FileOutputStream("./zkm-live/html/freemarker/test0.html");// 打印到文件
writer = new OutputStreamWriter(out);
temp.process(root, writer);
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
out.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// Note: Depending on what `out` is, you may need to call `out.close()`.
// This is usually the case for file output, but not for servlet output.
}
}
最终生成的html页面如下:
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome Big Joe!</h1>
<p>Our latest product:
<a href="products/greenmouse.html">green mouse</a>!
</body>
</html>
© 著作权归作者所有