使用Freemark先導包
<dependency>
<groupId>freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.9</version>
</dependency>
先來一個可以自動生成的類
public static void main(String[] args) throws IOException, TemplateException {
String dir ="E:\\prije\\xiaowu\\TestMyfreemark\\src\\main\\java\\com\\zhangzhi\\TestMain";
//這個dir 是項目的路徑掃描是模板和生成的都將在這個包下
Configuration conf = new Configuration();
//加載模板文件(模板的路徑)
conf.setDirectoryForTemplateLoading(new File(dir));
// 加載模板
Template template = conf.getTemplate("freemarker-demo.ftl");
// 定義數據
Map root = new HashMap();
root.put("world", "Hello World");//先來個最愛hello world
// 定義輸出
Writer out = new FileWriter(dir + "/freemarker.html");
template.process(root, out);
System.out.println("生成成功");
out.flush();
out.close();
}
這個是模板中的內容:可自行添加
<!DOCTYPE html>
<html lang="zh_CN">
<head>
<meta charset="UTF-8">
<title>${world}</title>
</head>
<body>
<table>
</body>
</html>
運行後生成的html爲
<!DOCTYPE html>
<html lang="zh_CN">
<head>
<meta charset="UTF-8">
<title>Hello World</title>
</head>
<body>
<table>
</body>
</html>
下面展示一下常用的:集合&類
{
String dir = "E:\\prije\\xiaowu\\TestMyfreemark\\src\\main\\java\\com\\zhangzhi\\TestMain";
Configuration conf = new Configuration();
//加載模板文件(模板的路徑)
conf.setDirectoryForTemplateLoading(new File(dir));
// 加載模板
Template template = conf.getTemplate("freemarker-demo.ftl");
// 定義數據
Student stu1 = new Student();
stu1.setId(1);
stu1.setName("一號兄弟");
Student stu2 = new Student();
stu2.setId(2);
stu2.setName("二號兄弟");
List<Student> people = new ArrayList<Student>();
people.add(stu1);
people.add(stu2);
Map root = new HashMap();
root.put("world", "Hello World");
root.put("people",people);
// 定義輸出
Writer out = new FileWriter(dir + "/freemarker.html");
template.process(root, out);
System.out.println("生成成功");
out.flush();
out.close();
}
模板內容
<!DOCTYPE html>
<html lang="zh_CN">
<head>
<meta charset="UTF-8">
<title>${world}</title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<table>
<tr>
<th>編號</th>
<th>名字</th>
</tr>
<#list people as p>
<tr style="color: <#if p_index%2==0>red<#else>blue</#if>">
<td>${p.id}</td>
<td>${p.name}</td>
</tr>
</#list>
</table>
</body>
</html>
生成的結果:
<!DOCTYPE html>
<html lang="zh_CN">
<head>
<meta charset="UTF-8">
<title>Hello World</title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<table>
<tr>
<th>編號</th>
<th>名字</th>
</tr>
<tr style="color: red">
<td>1</td>
<td>一號兄弟</td>
</tr>
<tr style="color: blue">
<td>2</td>
<td>二號兄弟</td>
</tr>
</table>
</body>
</html>
總結:
FreeMarker 是一個模板引擎,一個基於模板生成文本輸出的通用工具,使用純 Java 編寫,FreeMarker 被設計用來生成 HTML Web 頁面,特別是基於 MVC 模式的應用程序,雖然 FreeMarker 具有一些編程的能力,但通常由 Java 程序準備要顯示的數據,由FreeMarker 生成頁面,通過模板顯示準備的數據
FreeMarker 不是一個 Web 應用框架,而適合作爲 Web 應用框架一個組件。FreeMarker 與容器無關,因爲它並不知道 HTTP 或 Servlet;FreeMarker 同樣可以應用於非Web應用程序環境,FreeMarker 更適合作爲 Model2 框架(如 Struts)的視圖組件,你也可以在模板中使用 JSP標記庫。另外,FreeMarker是免費的。
應用場景
比較適合運用在訪問量大(或頁面數據量大),但是數據很少與後臺進行交互(即對實時性要求不是很高的)的頁面,比如商品網站上的商品詳情頁等。