freemarker的介紹與使用
一、什麼是freemarker
FreeMarker是一個用Java語言編寫的模板引擎,它基於模板來生成文本輸出。FreeMarker與Web容器無關,即在Web運行時,它並不知道Servlet或HTTP。它不僅可以用作表現層的實現技術,而且還可以用於生成XML,JSP或Java 等。
目前企業中:主要用Freemarker做靜態頁面或是頁面展示
二、Freemarker的使用方法
把freemarker的jar包添加到工程中
Maven工程添加依賴
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
原理:
使用步驟:
第一步:創建一個Configuration對象,直接new一個對象。構造方法的參數就是freemarker對於的版本號。
// 第一步:創建一個Configuration對象,直接new一個對象。構造方法的參數就是freemarker對於的版本號。
Configuration configuration = new Configuration(Configuration.getVersion());
第二步:設置模板文件所在的路徑。
後序的所有模板文件都放在此目錄下
// 第二步:設置模板文件所在的路徑。
configuration.setDirectoryForTemplateLoading(
new File("F:/dianshang/e3-item-web/src/main/webapp/WEB-INF/ftl"));
第三步:設置模板文件使用的字符集。一般就是utf-8.
// 第三步:設置模板文件使用的字符集。一般就是utf-8.
configuration.setDefaultEncoding("utf-8");
第四步:加載一個模板,創建一個模板對象。
// 第四步:加載一個模板,創建一個模板對象。
Template template = configuration.getTemplate("hello.ftl");
第五步:創建一個模板使用的數據集,可以是pojo也可以是map。一般是Map。
// 第五步:創建一個模板使用的數據集,可以是pojo也可以是map。一般是Map。
Map dataModel = new HashMap<>();
// 向數據集中添加數據
dataModel.put("hello", "this is my first freemarker test.");
第六步:創建一個Writer對象,一般創建一FileWriter對象,指定生成的文件名。
在本地磁盤上創建一個文件夾,用來保存生成的文件
// 第六步:創建一個Writer對象,一般創建一FileWriter對象,指定生成的文件名。
Writer out = new FileWriter(new File("F:/test/freemarker/hello.txt"));
第七步:調用模板對象的process方法輸出文件。
// 第七步:調用模板對象的process方法輸出文件。
template.process(dataModel, out);
第八步:關閉流。
// 第八步:關閉流。
out.close();
查看結果
三、freemarker模板的語法
3.1 訪問map中的key
${key}
案例如上
3.2 訪問pojo中的屬性
創建pojo實體
public class Student {
private Integer id;
private String name;
private Integer age;
private String address;
。。。 get set方法
public Student(Integer id, String name, Integer age, String address) {
super();
this.id = id;
this.name = name;
this.age = age;
this.address = address;
}
public Student(){
}
}
創建模板對象
代碼:
@Test
public void testFreeMarkerPojo() throws Exception {
// 第一步:創建一個Configuration對象,直接new一個對象。構造方法的參數就是freemarker對於的版本號。
Configuration configuration = new Configuration(Configuration.getVersion());
// 第二步:設置模板文件所在的路徑。
configuration.setDirectoryForTemplateLoading(
new File("F:/dianshang/e3-item-web/src/main/webapp/WEB-INF/ftl"));
// 第三步:設置模板文件使用的字符集。一般就是utf-8.
configuration.setDefaultEncoding("utf-8");
// 第四步:加載一個模板,創建一個模板對象。
Template template = configuration.getTemplate("student.ftl");
// 第五步:創建一個模板使用的數據集,可以是pojo也可以是map。一般是Map。
Map dataModel = new HashMap<>();
// 向數據集中添加數據
//創建一個pojo對象
Student student = new Student(1,"小明",18,"北京");
dataModel.put("student", student);
// 第六步:創建一個Writer對象,一般創建一FileWriter對象,指定生成的文件名。
Writer out = new FileWriter(new File("F:/test/freemarker/student.html"));
// 第七步:調用模板對象的process方法輸出文件。
template.process(dataModel, out);
// 第八步:關閉流。
out.close();
}
結果:
3.3 取集合中的數據
<#list studentList as student>
${student.id}/${studnet.name}
</#list>