
1 flt頁面
<html>
<head>
<title></title>
</head>
<body>
<h1>${person.title}</h1>
<h2>${person.time}</h2>
<p>${person.name}</p>
</body>
</html>
2 pom檔案
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
3 java 檔案
package test;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
/**
* 測試FreeMarker生成HTML模闆
* @author LiangGzone
* @version 2014-01-08
*/
public class FreeMarkerTest {
public static void main(String[] args) throws IOException {
FreeMarkerTest test = new FreeMarkerTest();
PersonBean person = new PersonBean();
person.setName("楊一凡");
person.setTime("2019");
person.setTitle("标題測試");
Map map = new HashMap();
// person.loadData();
map.put("person", person);
boolean flag = test.createHTMLFile("C:/Users/hyk/Desktop/楊一凡/template.ftl","d:/liang/template.html", map);
System.out.print("==="+flag);
}
/**
* 根據ftl模闆檔案,生成靜态HTML檔案
* @param ftlPath FTL模闆檔案路徑,例如["c:/liang/template.ftl"]
* @param filePath 生成HMTL檔案路徑,例如["d:/liang/lianggzone.html"]
* @param data Map資料
* @return
*/
public boolean createHTMLFile(String ftlPath, String filePath, Map data) {
Writer out = null;
//擷取HMTL檔案目錄
String fileDirectory = StringUtils.substringBeforeLast(filePath, "/");
//擷取HMTL檔案名
String fileName = StringUtils.substringAfterLast(filePath, "/");
String ftlDirectory = StringUtils.substringBeforeLast(ftlPath, "/");
String ftlName = StringUtils.substringAfterLast(ftlPath, "/");
try {
//檔案遞歸建立生成檔案目錄
File realDirectory = new File(fileDirectory);
if (!realDirectory.exists()) {
realDirectory.mkdirs();
}
//step1 擷取freemarker的配置
Configuration freemarkerCfg = new Configuration();
//step2 設定freemarker模闆所放置的位置(檔案夾)
freemarkerCfg.setDirectoryForTemplateLoading(new File(ftlDirectory));
//step3 設定freemarker模闆編碼
freemarkerCfg.setEncoding(Locale.getDefault(), "utf-8");
//step4 找到對應freemarker模闆并執行個體化
Template template = freemarkerCfg.getTemplate(ftlName);
//step5 初始化一個IO流
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(filePath)), "utf-8"));
//step6 模闆渲染出所要的内容
template.process(data, out);
} catch (TemplateException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
} finally{
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
}
4