码迷,mamicode.com
首页 > 其他好文 > 详细

freemarker入门例子

时间:2014-12-23 21:19:22      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:freemarker

freemarker入门例子,直接代码如下:

FreeMarkerTest


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{   
        // TODO Auto-generated method stub   
        Configuration config = new Configuration();   
        try {   
            config.setDirectoryForTemplateLoading(new File("e:\\javasrc"));   
            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.google.com");   
            product.put("name", "green hose");   
            File file = new File("e:\\javasrc\\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();   
        }   
    }   
  
}  


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>  



freemarker入门例子

标签:freemarker

原文地址:http://blog.csdn.net/u014723529/article/details/42107245

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!