首页 > 代码库 > freemark生成静态页面

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>  
View Code

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 = http://www.mamicode.com/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");      }  }  
View Code