六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 121|回复: 0

freemarker生成静态html页面

[复制链接]

升级  46%

5

主题

5

主题

5

主题

童生

Rank: 1

积分
23
 楼主| 发表于 2013-2-7 19:32:43 | 显示全部楼层 |阅读模式
                       1.加入对应的包——>fremarker.jar
                       2.开发一个模板
                            src/templates下创建demo.ftl文件
                            写入
  
<!DOCTYPE HTML PUBLIC  "-//W<?xml:namespace prefix = st1 ns = "urn:schemas-microsoft-com:office:smarttags" /><chmetcnv w:st="on" tcsc="0" numbertype="1" negative="False" hasspace="False" sourcevalue="3" unitname="C">3C</chmetcnv>//DTD  HTML 4.01 Transitional//EN"<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

  
"http://www.w3.org/TR/html4/loose.dtd">

  
<html>

  
<head>

  
<meta http-equiv="Content-Type"  content="text/html; charset=gb2312">

  
<title>无标题文档</title>

  
</head>

  
<body  align="center">

  
${userName},欢迎你!

  
<#list list as  name>

  
${name}<br/>

  
</#list>

  
</body>

  </html>
  
 

  
3.开发一个测试类:
       Test.java

        

  package test;

   

  import  java.io.BufferedWriter;

  import  java.io.File;

  import  java.io.FileWriter;

  import  java.io.IOException;

  import  java.io.PrintWriter;

  import  java.util.HashMap;

  import  java.util.Map;

   

  import  freemarker.template.Configuration;

  import  freemarker.template.DefaultObjectWrapper;

  import  freemarker.template.Template;

  import  freemarker.template.TemplateException;

  public class test  {

  public static  void main(String[] args) {

           try {  

          Configuration config=new  Configuration();

          File file=new  File("src/templates");  

          //设置要解析的模板所在的目录,并加载模板文件  

           config.setDirectoryForTemplateLoading(file);  

          //设置包装器,并将对象包装为数据模型  

          config.setObjectWrapper(new  DefaultObjectWrapper());   

          //添加数据             

           Map<String,Object> root=new  HashMap<String, Object>();  

              List  list=new ArrayList();

                     list.add(“tom”);

                     list.add(“jack”);

                     root.put("userName",”TOM”  ); 

                     root.put(“list”,list);

   

          PrintWriter out = new PrintWriter(new  BufferedWriter(

                                       new  FileWriter("src/templates" + "\\out.html")));

          Template  template=config.getTemplate("demo.ftl");

          //合并数据模型与模板  

          template.process(root, out);  

          out.flush();  

          out.close();

      } catch (IOException e) {  

          e.printStackTrace();  

      }catch (TemplateException e) {  

          e.printStackTrace();  

      }}}

   

  
 

4.执行main方法:
在src/templates生成out.html文件。
 

点击文件:
TOM,欢迎你!

tom
jack
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表