测试FreeMarker(初探)

先写一个类:HelloWorld.java

/*
 * HelloWorld.java
 *
 * Created on 2007年9月4日, 下午9:30
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

/**
 *
 * @author Administrator
 */

import java.util.*; 

import java.io.*; 

import freemarker.template.*;

public class HelloWorld{ 

   private Configuration cfg;  

   public Configuration getCfg() { 

       return cfg; 

   } 

   public void init() throws Exception{ 

       cfg = new Configuration(); 

       cfg.setDirectoryForTemplateLoading(new File("D:/freemarker_project/template")); 

   } 

   public static void main(String[] args) throws Exception 

   { 

       HelloWorld obj = new HelloWorld(); 

       obj.init(); 

       Map root = new HashMap();       

       Template t = obj.getCfg().getTemplate("helloworld.ftl"); 

       Writer ut = new OutputStreamWriter(new FileOutputStream("D:/freemarker_project/out/helloword.html"),"GBK");   

       t.process(root,ut); 

       System.out.println("Successfull……………."); 

   } 

}

 

在D:/freemarker_project/template目录中建立一个helloworld.ftl文件

文件内容为

<#macro greet person>

 Hello ${person}!

</#macro>

<html>

<head>

 <title>Hello World</title>

</head>

<body>

<@greet person="测试"/>

</body>

</html>

 

直接运行HelloWorld.java类,你将会在D:/freemarker_project/out/目录下找到helloword.html文件

文件源文件内容为:

<html>

<head>

 <title>Hello World</title>

</head>

<body>

 Hello 测试!

</body>

</html>

Advertisements

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

%d 博主赞过: