俗話說(shuō)萬(wàn)事開(kāi)頭難,這句話對(duì)于我們程序員來(lái)說(shuō)非常的適用,剛接觸一門(mén)新的東西,在初步了解了一些基本的東西后,都像找點(diǎn)東西練練手,找點(diǎn)熟悉的感覺(jué)。而我最近的兩年多的時(shí)間一直在從事Eclipse插件的工作,對(duì)Web 應(yīng)用開(kāi)發(fā)接觸比較少,發(fā)現(xiàn)只有C/S開(kāi)發(fā)的經(jīng)驗(yàn)想換個(gè)工作環(huán)境比較困難。所以覺(jué)得學(xué)習(xí)一下Web的開(kāi)發(fā)知識(shí)對(duì)自己比較有好處。
FreeMarker是一個(gè)模板引擎,一個(gè)基于模板生成文本輸出的通用工具,FreeMarker被設(shè)計(jì)用來(lái)生成HTML Web頁(yè)面,特別是基于MVC模式的應(yīng)用程序,關(guān)于FreeMarker的更多的介紹,可以訪問(wèn)它的主頁(yè)或者在百度百科中搜索相關(guān)的詞條(點(diǎn)這里).
首先新建一個(gè)Java工程,比如FreeMarkerTest,將FreeMarker的jar包添加至工程的構(gòu)建路徑中,然后新建一個(gè)文件夾template存放模板文件的,下面是我們的模板的內(nèi)容,名稱為“test.ftl":<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome ${user}!</h1>
<p>Our latest product:
<a href="${latestProduct.url}">${latestProduct.name} </a>!
</body>
</html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome ${user}!</h1>
<p>Our latest product:
<a href="${latestProduct.url}">${latestProduct.name} </a>!
</body>
</html>
在新建一個(gè)Java類(lèi),名稱為FreeMarkerTest.java:
package test;
import freemarker.template.*;
import java.util.*;
import java.io.*;
public class FreeMarkerTest {
public static void main(String[] args) throws Exception {
/* 創(chuàng)建配置 */
Configuration cfg = new Configuration();
/* 指定模板存放的路徑*/
cfg.setDirectoryForTemplateLoading(new File("template"));
cfg.setObjectWrapper(new DefaultObjectWrapper());
/* 從上面指定的模板目錄中加載對(duì)應(yīng)的模板文件*/
Template temp = cfg.getTemplate("test.ftl");
/* 創(chuàng)建數(shù)據(jù)模型 */
Map root = new HashMap();
root.put("user", "Big Joe");
Map latest = new HashMap();
root.put("latestProduct", latest);
latest.put("url", "products/greenmouse.html");
latest.put("name", "green mouse");
/* 將生成的內(nèi)容打印到控制臺(tái)中 */
Writer out = new OutputStreamWriter(System.out);
temp.process(root, out);
out.flush();
}
}
import freemarker.template.*;
import java.util.*;
import java.io.*;
public class FreeMarkerTest {
public static void main(String[] args) throws Exception {
/* 創(chuàng)建配置 */
Configuration cfg = new Configuration();
/* 指定模板存放的路徑*/
cfg.setDirectoryForTemplateLoading(new File("template"));
cfg.setObjectWrapper(new DefaultObjectWrapper());
/* 從上面指定的模板目錄中加載對(duì)應(yīng)的模板文件*/
Template temp = cfg.getTemplate("test.ftl");
/* 創(chuàng)建數(shù)據(jù)模型 */
Map root = new HashMap();
root.put("user", "Big Joe");
Map latest = new HashMap();
root.put("latestProduct", latest);
latest.put("url", "products/greenmouse.html");
latest.put("name", "green mouse");
/* 將生成的內(nèi)容打印到控制臺(tái)中 */
Writer out = new OutputStreamWriter(System.out);
temp.process(root, out);
out.flush();
}
}
這樣就可以了,運(yùn)行后在控制臺(tái)可以打印:
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome Big Joe!</h1>
<p>Our latest product:
<a href="products/greenmouse.html">green mouse</a>!
</body>
</html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome Big Joe!</h1>
<p>Our latest product:
<a href="products/greenmouse.html">green mouse</a>!
</body>
</html>