FreeMarker 模板靜態化
使用freemarker將頁面生成html文件,本節測試html文件生成的方法:
1、使用模板文件靜態化 定義模板文件,使用freemarker靜態化程序生成html文件。
2、使用模板字符串靜態化 定義模板字符串,使用freemarker靜態化程序生成html文件。
@SpringBootTest(classes = FreemarkerTest.class)
@RunWith(SpringRunner.class)
public class FreemarkerTest {
// 靜態化 基於ftl模板文件生成HTML文件
@Test
public void testGenerateHtml() throws Exception {
// 得到配置類
Configuration configuration = new Configuration(Configuration.getVersion());
// 獲得classPath路徑
String classPath = this.getClass().getResource("/").getPath();
// 設置模板加載路徑
configuration.setDirectoryForTemplateLoading(new File(classPath + "/templates/"));
// 獲取模板
Template template = configuration.getTemplate("test1.ftl");
// 模板數據
Map<String, Object> map = getMap();
// 靜態化
String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
InputStream inputStream = IOUtils.toInputStream(content);
FileOutputStream fileOutputStream = new FileOutputStream(new File("E:/test1.html"));
// 輸出文件
IOUtils.copy(inputStream, fileOutputStream);
inputStream.close();
fileOutputStream.close();
}
// 靜態化 基於模板文件內容(String)生成HTML文件
@Test
public void testGenerateHtmlByString() throws Exception {
// 得到配置類
Configuration configuration = new Configuration(Configuration.getVersion());
// 模板內容
String templateString = "<html>\n" +
" <head></head>\n" +
" <body>\n" +
" 名稱:${name}\n" +
" </body>\n" +
"</html>";
// 使用一個模板加載器變成模板
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
// 設置模板內容及名稱
stringTemplateLoader.putTemplate("template", templateString);
// 設置模板加載器
configuration.setTemplateLoader(stringTemplateLoader);
// 獲取template內容
Template template = configuration.getTemplate("template", "utf-8");
// 模板數據
Map<String, Object> map = getMap();
// 靜態化
String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
InputStream inputStream = IOUtils.toInputStream(content);
FileOutputStream fileOutputStream = new FileOutputStream(new File("E:/test2.html"));
// 輸出文件
IOUtils.copy(inputStream, fileOutputStream);
inputStream.close();
fileOutputStream.close();
}
// 設置模板數據
public static Map<String, Object> getMap() {
Map<String, Object> map = new HashMap<>();
map.put("name", "11");
Student stu1 = new Student();
stu1.setName("小明");
stu1.setAge(18);
stu1.setMoney(1000.86f);
stu1.setBirthday(new Date());
Student stu2 = new Student();
stu2.setName("小紅");
stu2.setMoney(200.1f);
stu2.setAge(19); //
stu2.setBirthday(new Date());
List<Student> friends = new ArrayList<>();
friends.add(stu1);
stu2.setFriends(friends);
stu2.setBestFriend(stu1);
List<Student> stus = new ArrayList<>();
stus.add(stu1);
stus.add(stu2); //向數據模型放數據
map.put("stus", stus); //準備map數據
HashMap<String, Student> stuMap = new HashMap<>();
stuMap.put("stu1", stu1);
stuMap.put("stu2", stu2); //向數據模型放數據
map.put("stu1", stu1); //向數據模型放數據
map.put("stuMap", stuMap); //返回模板文件名稱
return map;
}
}