1.新建一个maven项目
<!-- 导入freemarker的依赖包 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
2.创建一个ftl文件夹专门存放模板
3.新建一个infopub.ftl模板
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name='viewport'
content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
<title>Freemarker生成静态页面Demo展示</title>
<style type="text/css">
article {
padding: 20px;
}
address {
font-style: normal;
text-align: right;
width: 100%;
color: #999999;
}
.author {
float: left;
}
.seeNum {
float: left;
}
.seeIcon{
float: left;
margin-left: 10px;
}
.img {
width: 380px;
height: 380px;
}
</style>
</head>
<body>
<article>
<h2>${title}</h2>
<address>
<span class="author">${author} ${publishTime}</span>
<span class="seeIcon">${seeIcon}</span>
<span class="seeNum">${seeNum}</span>
</address>
<br>
<img src="${imgPath}" class="img"/>
<p>${content}</p>
</article>
</body>
</html>
4.模板生成HTML静态页面的工具类
public class FreemarkerUtil {
private static final Configuration cfg;
static {
cfg = new Configuration(Configuration.VERSION_2_3_23);
try {
// 设置模板路径
cfg.setDirectoryForTemplateLoading(new File("H:\\freemarkerdemo\\src\\main\\resources"));
// 设置默认编码
cfg.setDefaultEncoding("utf-8");
//若发生错误,HTML_DEBUG_HANDLER会生成错误信息到生成页面;RETHROW_HANDLER错误信息会输出到控制台
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @param modeName 模板名称
* @param targetFileName 生成后的HTML名称
* @param params 传入模板的参数
* @Author: mpy
* @Date: 2020/7/20
* @Description:生成静态页面
*/
public static void createHtmlByMode(String modeName, String targetFileName, Map<String, Object> params) throws Exception {
Writer out = null;
//找到服务器缓存目录,可以自己指定目录
String folder = "H:\\freemarkerdemo\\src\\main\\resources\\static";
//通过匹配路径格式拼接完整生成路径
String outFile = folder + File.separator + targetFileName;
try {
File file = new File(outFile);
//生成空HTML文件
if (!file.exists()) {
file.createNewFile();
}
// 创建模版对象
Template template = cfg.getTemplate(modeName);
// 设置输出流
out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");// 设置编码 UTF-8
// 模版数据插入参数,通过输出流插入到HTML中
template.process(params, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != out) {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
5.在main方法里模拟动态数据生成静态页面
@Test
public void test() throws Exception {
Map<String, Object> params = new HashMap<String, Object>();
params.put("title", "freemark测试Demo");
params.put("author", "mpy");
params.put("publishTime", "2020-7-20");
params.put("seeIcon", "000");
params.put("seeNum", "888");
params.put("imgPath", "http://www.mgpjy666666.xyz/img/123.jpg");
params.put("content", "这是一个简单的Freemarker动态数据静态化的Demo");
FreemarkerUtil.createHtmlByMode("ftl/infopub.ftl", "test.html", params);
}