freemarker入门例子,直接代码如下:
FreeMarkerTest.java
class="java">package com.bijian.study.freemark; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; 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.DefaultObjectWrapper; import freemarker.template.Template; public class FreeMarkerTest { /** * @param args */ public static void main(String[] args) throws Exception{ Configuration config = new Configuration(); try { //URL path = FreeMarkerTest.class.getResource(""); String path = new File("").getAbsolutePath(); config.setDirectoryForTemplateLoading(new File(path)); config.setObjectWrapper(new DefaultObjectWrapper()); Template template = config.getTemplate("test.ftl","UTF-8"); //创建数据模型 Map root = new HashMap(); List<User> users = new ArrayList<User>(); User u1 = new User(); u1.setId("123"); u1.setName("王五"); users.add(u1); User u2 = new User(); u2.setId("2345"); u2.setName("张三"); User u3 = new User(); u3.setId("fgh"); u3.setName("李四"); users.add(u2); users.add(u3); root.put("userList", users); Map product = new HashMap(); root.put("lastProduct", product); product.put("url", "http://www.baidu.com"); product.put("name", "green hose"); File file = new File(path + "\\test.html"); if(!file.exists()){ //System.out.println("file exist"); file.createNewFile(); } Writer out = new BufferedWriter(new FileWriter(file)); template.process(root, out); out.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
User.java
package com.bijian.study.freemark; public class User { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
test.ftl
<html> <head> <title>Welcome!</title> </head> <body> <#list userList as user> <h1>Welcome ${user.name}! id:${user.id}</h1><br/> </#list> <p>Our latest product: <a href="${lastProduct.url}">${lastProduct.name} </a>! </body> </html>
工程目录结构:
运行FreeMarkerTest.java后,将在工程下生成一个test.html文件。文件内容如下:
<html> <head> <title>Welcome!</title> </head> <body> <h1>Welcome 王五! id:123</h1><br/> <h1>Welcome 张三! id:2345</h1><br/> <h1>Welcome 李四! id:fgh</h1><br/> <p>Our latest product: <a href="http://www.baidu.com">green hose </a>! </body> </html>
浏览器打开test.html文件,效果如下:
?
文章来源:http://yonglailizhi.iteye.com/blog/656403#