freemarker模版和数据模型



freemarker模版和数据模型

freemarker就是一中文本输出方式,freemarker就是通过“模版+数据模型=输出”的方式来实现文本输出。
假如我们需要一个静态页
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>welcom!</title>
</head>
<body>
<h>welcom RU</h>
<p>our last prouduct:<a href=”products/greenmouse.html”>green mouse</a></p>
</body>
</html>
由于静态页不能实现数据的交互,所以我们要把页面中的数据交互部分用动态的方式实现。freemarker可以利用模版来实现它。freemarker的模版也是静态文件,但是可以利用freemarker指令做到动态效果。
(1) freemarker的代码可以写成如下模版:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>welcom!</title>
</head>
<body>
<h>welcom ${user}</h>
<p>our last prouduct:<a href=”${lastproduct.url}”>${lastproduct.name}</a></p>
</body>
</html>
模版完成,这样我们就可以动态的实现数据交互。
(2)下面就可以创建数据模型:
数据模型的作用就是为模版提供数据。在创建freemarker的数据模型的数据模型时,只需要导入java.lang 和java.util包。利用hashMap来存放数据。
代码如下:
Map root=new HashMap();
root.put(“user”,”RU”);
Map product=new HashMap();
product.put(“url”,”products/greenmouse.html”);
product.put(“name”,”green mouse”);
root.put(“lastproduct”,product);