freemark生成静态页面

到freemark的官方网站下载:

http://sourceforge.net/projects/freemarker/files/freemarker/2.3.20/freemarker-2.3.20.tar.gz/download

建一个web project,如下:

建成的项目结构如下:

模板文件如下(test.ftl):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
  <head>      
    <title>My JSP 'index.jsp' starting page</title>  
 <meta http-equiv="pragma" content="no-cache">  
 <meta http-equiv="cache-control" content="no-cache">  
 <meta http-equiv="expires" content="0">      
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
 <meta http-equiv="description" content="This is my page">  
  </head>  
  <body>  
   The first test: ${persion}  
  </body>  
</html>  
Test.java:

import java.io.File;  
import java.io.FileOutputStream;  
import java.io.OutputStreamWriter;  
import java.io.Writer;  
import java.util.HashMap;  
import java.util.Map;  
import freemarker.template.Configuration;  
import freemarker.template.DefaultObjectWrapper;  
import freemarker.template.Template;  
import freemarker.template.TemplateExceptionHandler;  
public class Test {  
    public static void main(String[] args) throws Exception{  
        //模板路径  
        String realpath = System.getProperty("user.dir");
        File savefile = new File(new File(realpath), "WebContent/WEB-INF/freemark");
        String dir = savefile.getAbsolutePath();
        Configuration cfg = new Configuration(); 
        //加载freemarker模板文件  
        cfg.setDirectoryForTemplateLoading(new File(dir));  
        //设置对象包装器  
        cfg.setObjectWrapper(new DefaultObjectWrapper());  
        //设计异常处理器          cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);  
        //定义并设置数据  
        Map<String, String> data = new HashMap<String, String>();  
        data.put("persion", "小明");  
        //获取指定模板文件  
        Template template = cfg.getTemplate("test.ftl");  
        //定义输入文件,默认生成在工程根目录  
        Writer out = new OutputStreamWriter(new FileOutputStream("test.html"),"GBK");  
        //最后开始生成  
        template.process(data, out);  
        System.out.println("successful");  
    }  
}  



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值