1. 程式人生 > >Freemarker使用教程——入門篇

Freemarker使用教程——入門篇

一.簡介

FreeMarker 是一個模板引擎,一個基於模板生成文字輸出的通用工具,使用純 Java 編寫,FreeMarker 被設計用來生成 HTML Web 頁面,特別是基於 MVC 模式的應用程式,雖然 FreeMarker 具有一些程式設計的能力,但通常由 Java 程式準備要顯示的資料,由FreeMarker 生成頁面,通過模板顯示準備的資料

FreeMarker 不是一個 Web 應用框架,而適合作為 Web 應用框架一個元件。FreeMarker 與容器無關,因為它並不知道 HTTP 或 Servlet;FreeMarker 同樣可以應用於非Web應用程式環境,FreeMarker 更適合作為 Model2 框架(如 Struts)的檢視元件,你也可以在模板中使用 JSP標記庫。另外,FreeMarker是免費的。

2.應用場景

比較適合運用在訪問量大(或頁面資料量大),但是資料很少與後臺進行互動(即對實時性要求不是很高的)的頁面,比如商品網站上的商品詳情頁等。

3.前期準備

要想使用freemarker,首先必須要有freemarker的jar包,這個網際網路上隨處可以下載,這邊就不多說

<dependency>
<groupId>freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.9</version>
</dependency>


4.入門demo

(1)建立一個testFreemarker類

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;


/**
 * @作者:JackHisen(GWD)
 * @專案名:freemarker
 * @時間:2017-7-25 下午2:39:45
 * @version 1.0
 */
public class testFreemarker {
	public static void main(String[] args) throws Exception {
		String dir="H:\\Java-EE Workspace\\freemarker\\src\\com\\gwd\\freemarker";
		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");
		// 定義輸出
		Writer out = new FileWriter(dir + "/freemarker.html");
		template.process(root, out);
		System.out.println("轉換成功");
		out.flush();
		out.close();
	}
}

專案目錄如下,其中freemarker.html檔案是執行main函式後自動生成的,freemarker-demo.ftl為模板

(2)freemarker模板中寫入內容

(3)生成的html頁面:


5.其他資料型別

1.實體bean

(1)建立Person類

public class Person {
	private int id;
	private String name;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}
(2)testFreemarker
public class testFreemarker {
	public static void main(String[] args) throws Exception {
		String dir="H:\\Java-EE Workspace\\freemarker\\src\\com\\gwd\\freemarker";
		Configuration conf = new Configuration();
		//載入模板檔案(模板的路徑)
		conf.setDirectoryForTemplateLoading(new File(dir));
		// 載入模板
		Template template = conf.getTemplate("/freemarker-demo.ftl");
		// 定義資料
		
		Person person=new Person();
		person.setId(1);
		person.setName("小明");
		Map root = new HashMap();
		root.put("person", person);
		// 定義輸出
		Writer out = new FileWriter(dir + "/freemarker.html");
		template.process(root, out);
		System.out.println("轉換成功");
		out.flush();
		out.close();
	}
}

(3)Freemarker模板
${person.id}
${person.name}

(4)生成的html頁面


2.List集合

(1)testFreemarker

public class testFreemarker {
	public static void main(String[] args) throws Exception {
		String dir="H:\\Java-EE Workspace\\freemarker\\src\\com\\gwd\\freemarker";
		Configuration conf = new Configuration();
		//載入模板檔案(模板的路徑)
		conf.setDirectoryForTemplateLoading(new File(dir));
		// 載入模板
		Template template = conf.getTemplate("/freemarker-demo.ftl");
		// 定義資料
		
		Person p1=new Person();
		p1.setId(1);
		p1.setName("小明");
		Person p2=new Person();
		p2.setId(2);
		p2.setName("小華");
		List<Person> person=new ArrayList<Person>();
		person.add(p1);
		person.add(p2);
		Map root = new HashMap();
		root.put("person", person);
		// 定義輸出
		Writer out = new FileWriter(dir + "/freemarker.html");
		template.process(root, out);
		System.out.println("轉換成功");
		out.flush();
		out.close();
	}
}

(2)模板
<#list person as p>
${p.id}/${p.name}
</#list>

(3)生成的html檔案

3.Map集合

1.testFreemarker

public class testFreemarker {
	public static void main(String[] args) throws Exception {
		String dir="H:\\Java-EE Workspace\\freemarker\\src\\com\\gwd\\freemarker";
		Configuration conf = new Configuration();
		//載入模板檔案(模板的路徑)
		conf.setDirectoryForTemplateLoading(new File(dir));
		// 載入模板
		Template template = conf.getTemplate("/freemarker-demo.ftl");
		// 定義資料
		
		Map root = new HashMap();
		Map mxs = new HashMap();
		mxs.put("fbb","范冰冰");
		mxs.put("lbb","李冰冰");

		root.put("mxs",mxs);

		// 定義輸出
		Writer out = new FileWriter(dir + "/freemarker.html");
		template.process(root, out);
		System.out.println("轉換成功");
		out.flush();
		out.close();
	}
}

2.模板(兩種寫法)
${mxs.fbb}/${mxs.lbb}


<#list mxs?keys as k>
   ${mxs[k]}
</#list>

3.生成的html


4.List<Map>集合

1.testFreemarker

public class testFreemarker {
	public static void main(String[] args) throws Exception {
		String dir="H:\\Java-EE Workspace\\freemarker\\src\\com\\gwd\\freemarker";
		Configuration conf = new Configuration();
		//載入模板檔案(模板的路徑)
		conf.setDirectoryForTemplateLoading(new File(dir));
		// 載入模板
		Template template = conf.getTemplate("/freemarker-demo.ftl");
		// 定義資料
		
		Map root = new HashMap();
		List<Map> maps = new ArrayList<Map>();
		Map pms1 = new HashMap();
		pms1.put("id1", "范冰冰");
		pms1.put("id2", "李冰冰");
		Map pms2 = new HashMap();
		pms2.put("id1", "曾志偉");
		pms2.put("id2", "何炅");
		maps.add(pms1);
		maps.add(pms2);
		root.put("maps", maps);

		// 定義輸出
		Writer out = new FileWriter(dir + "/freemarker.html");
		template.process(root, out);
		System.out.println("轉換成功");
		out.flush();
		out.close();
	}
}
2.模板(2種)
<#list maps as m>
	${m.id1}/${m.id2}
</#list>


<#list maps as m>
	<#list m?keys as k>
		${m[k]}
	</#list>
</#list>

3.生成的html

5.獲得當前迭代的索引

(1)testFreemarker

public class testFreemarker {
	public static void main(String[] args) throws Exception {
		String dir="H:\\Java-EE Workspace\\freemarker\\src\\com\\gwd\\freemarker";
		Configuration conf = new Configuration();
		//載入模板檔案(模板的路徑)
		conf.setDirectoryForTemplateLoading(new File(dir));
		// 載入模板
		Template template = conf.getTemplate("/freemarker-demo.ftl");
		// 定義資料
		
		Map root = new HashMap();
		Person p1=new Person();
		p1.setId(1);
		p1.setName("李冰冰");
		Person p2=new Person();
		p2.setId(2);
		p2.setName("范冰冰");
		Person p3=new Person();
		p3.setId(3);
		p3.setName("沙冰冰");
		List<Person> list = new ArrayList<Person>();
		list.add(p1);
		list.add(p2);
		list.add(p3);
		root.put("persons", list);

		// 定義輸出
		Writer out = new FileWriter(dir + "/freemarker.html");
		template.process(root, out);
		System.out.println("轉換成功");
		out.flush();
		out.close();
	}
}

(2)模板
<#list persons as p>
	${p_index}
</#list>

(3)生成的html檔案


(6)在模板中進行賦值

(1)testFreemarker

package com.gwd.freemarker;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;


/**
 * @作者:JackHisen(GWD)
 * @專案名:freemarker
 * @時間:2017-7-25 下午2:39:45
 * @version 1.0
 */
public class testFreemarker {
	public static void main(String[] args) throws Exception {
		String dir="H:\\Java-EE Workspace\\freemarker\\src\\com\\gwd\\freemarker";
		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");

		// 定義輸出
		Writer out = new FileWriter(dir + "/freemarker.html");
		template.process(root, out);
		System.out.println("轉換成功");
		out.flush();
		out.close();
	}
}


(2)模板
<#assign x="${world}" />
${x}

<#assign x>
   <#list ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天"] as n>
      ${n}
   </#list>
</#assign>
${x}

(3)生成的html

7.if語句

(1)申明:一般情況下模板中的資料來源於後臺,但是這邊為了方便演示,所以資料都在模板中寫死了,後臺testFreemarker可以同上,但實際上map可以為空,只要確保能生成html頁面即可

(2)模板

<#list ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天"] as n>
<#if n != "星期一">
   ${n}
</#if>
</#list>


(3)生成的html檔案


8.else語句

(1)模板

<#list ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天"] as n>
<#if (n_index == 1) || (n_index == 3)>
   ${n} --紅色
<#else>
${n} --綠色
</#if>
</#list>

(2)生成的html

9.格式化日期

(1)testFreemarker

public class testFreemarker {
	public static void main(String[] args) throws Exception {
		String dir="H:\\Java-EE Workspace\\freemarker\\src\\com\\gwd\\freemarker";
		Configuration conf = new Configuration();
		//載入模板檔案(模板的路徑)
		conf.setDirectoryForTemplateLoading(new File(dir));
		// 載入模板
		Template template = conf.getTemplate("/freemarker-demo.ftl");
		// 定義資料
		
		Map root = new HashMap();
		
		root.put("cur_time",new Date());
			
		// 定義輸出
		Writer out = new FileWriter(dir + "/freemarker.html");
		template.process(root, out);
		System.out.println("轉換成功");
		out.flush();
		out.close();
	}
}


(2)日期模板
${cur_time?date}
生成html

(3)日期時間模板

${cur_time?datetime}
生成html

(4)時間模板

${cur_time?time}

生成html

10.對null的處理

(1)testFreemarker

public class testFreemarker {
	public static void main(String[] args) throws Exception {
		String dir="H:\\Java-EE Workspace\\freemarker\\src\\com\\gwd\\freemarker";
		Configuration conf = new Configuration();
		//載入模板檔案(模板的路徑)
		conf.setDirectoryForTemplateLoading(new File(dir));
		// 載入模板
		Template template = conf.getTemplate("/freemarker-demo.ftl");
		// 定義資料
		
		Map root = new HashMap();
		
		root.put("world",null);
			
		// 定義輸出
		Writer out = new FileWriter(dir + "/freemarker.html");
		template.process(root, out);
		System.out.println("轉換成功");
		out.flush();
		out.close();
	}
}

(2)null為空模板
${world!}         ——前面有個null
生成html


(3)為null時給預設值模板

${world!"如果world為null,我就會顯示"}
生成的html

11.巨集定義

(1)普通巨集定義

模板:

<#macro table u>
${u} 
</#macro>
<@table u="這個是巨集定義" />

生成的html

(2)擴充套件巨集定義

模板:

<#macro table u>
 ${u}
<#nested/>
</#macro>
<@table u=8 >我是擴充套件的巨集定義</@table>

生成的html