1. Create a common project to
2. Add dependence
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
3. Create a template freekamer.ftl
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<#--s-->
<h1>欢迎:${username}</h1>
<h1>年龄:${age}</h1>
</body>
</html>
4. Write test program generation static pages
package com.fuke.myTest;
import com.sun.org.apache.bcel.internal.generic.NEW;
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
public class MyTest {
public static void main(String[] args) {
/*
第一步:创建一个 Configuration 对象,直接 new 一个对象。构造方法的参数就是 freemarker的版本号。
第二步:设置模板文件所在的路径。
第三步:设置模板文件使用的字符集。一般就是 utf-8.
第四步:加载一个模板,创建一个模板对象。
第五步:创建一个模板使用的数据集,可以是 pojo 也可以是 map。一般是 Map。
第六步:创建一个 Writer 对象,一般创建一 FileWriter 对象,指定生成的文件名。
第七步:调用模板对象的 process 方法输出文件。
第八步:关闭流
*/
FileWriter fileWriter = null;
Configuration configuration = new Configuration(Configuration.getVersion());
try {
configuration.setDirectoryForTemplateLoading(new File("E:\\idea项目空间\\FreeMarkerDemo\\src\\main\\resources\\ftl"));
configuration.setDefaultEncoding("utf-8");
Template template = configuration.getTemplate("MyFreeMarker.ftl");
HashMap hashMap = new HashMap();
hashMap.put("username","张三");
hashMap.put("age",15);
fileWriter = new FileWriter(new File("E:" + File.separator + "myFreeMaker.html"));
template.process(hashMap,fileWriter);
}catch (Exception e){
e.printStackTrace();
}finally {
if(fileWriter!=null){
try {
fileWriter.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
assign command
assign command can define a variable or an object, can use these variables in the current page, and automatically generates html resolve to a value corresponding to
<#assign myName="dp" />
<#assign user={"name":"po","birthday":"2016"}/>
<span>${myName}</span> <br>
<span>${user.name}:${user.birthday}</span>
command list
list can be traversed to set or array, such as string stored strlist traversal format strList as str, $ {str_index} using the current iteration may be removed under standard
traversal general type set of strings
<#list strList as str>
${str_index}------${str}
</#list>
Traverse the object set type
<#list userList as user>
${user_index}------${user.name}
</#list>
if instruction
<#list userList as user>
<#if user.name="鲁班">
<h3>${user.name}---判断正确</h3>
<#else>
<h3>${user.name}----判断失败</h3>
</#if>
</#list>
include instruction
Instruction may include the introduction of other pages
<#include "test2.ftl">