月初寫了兩篇博客,瞅着月末了,發現自己一個寫博客的特點:越來越喜歡開門見山,不喜歡拐彎抹角了!!!所以,這裏就不說爲什麼我會學習freemaker了!
一、配置環境
直接將下載的freemarker下的兩個文件拷貝到eclipse的主目錄下面freemarker下的兩個文件:
Features
Plugins
C:\Java\tool\eclipse:
二、開發流程
1)、引入freemarker的jar包:
<dependency><groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.20</version>
</dependency>
2)、創建相應的ftl模板文件,注意,文件名一定是ftl格式的
src.mian.resource.ftl.hello.ftl
Hello:${username}
src.mian.resource.ftl.hello.ftl
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Hello:${user.userName}</h1>
${user.nicekName}年紀已經${user.age}
</body>
</html>
3)、測試方法
@Test
public void testFHello() {
try {
// 1、創建Configuration
Configuration cfg = new Configuration();
// 2、設置config中加載模板的路徑
// 設置了基於classpath加載路徑,並且所有的模板文件都放在/ftl中
cfg.setClassForTemplateLoading(TestFreemarker.class, "/ftl");
// 3、獲取模板文件,由於已經設置了默認的路徑是/ftl,此時hello.ftl就是ftl下的文件
Template temp = cfg.getTemplate("helloHtml.ftl");
// 4、創建數據文件,非常類似於OGNL,使用map來進行設置
Map<String, Object> root = new HashMap<String, Object>();
root.put("username", "zll");
// 5、通過模板和數據文件生成相應的輸出
temp.process(root, new FileWriter("d:/test/hello.html"));
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
}
4)、結果
三、小結
在JSP之前,用servelet寫html頁面怎麼寫?將html的標籤作爲整個輸出流的一部分,不斷的在servlet中拼寫html的內容,然後嵌入相對應的數據內容,有了jsp之後,jsp對html標籤和數據做了一個整合,而freemarker恰是在jsp之前,通過寫好的html模板和數據,動態生成靈活頁面。所以,如果沒人攔着我,那麼我覺得freemarker更像一個寫好了html標籤的servlet!!!有疑問麼???
(下篇進行freemarker的封裝)