从零学习freemarker(2)给模板传递参数的测试

原文:http://www.java2000.net/p7841

程序代码
 

  1. package freemarker;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.OutputStreamWriter;
  5. import java.io.Writer;
  6. import java.util.HashMap;
  7. import java.util.Map;
  8. import freemarker.template.Configuration;
  9. import freemarker.template.Template;
  10. public class Test2 {
  11.   private Configuration cfg;
  12.   public Configuration getCfg() {
  13.     return cfg;
  14.   }
  15.   public void init() throws Exception {
  16.     cfg = new Configuration();
  17.     cfg.setDirectoryForTemplateLoading(new File("bin/freemaker"));
  18.   }
  19.   public static void main(String[] args) throws Exception {
  20.     Test2 obj = new Test2();
  21.     obj.init();
  22.     Map root = new HashMap();
  23.     root.put("user""java2000.net");
  24.     Map latestProduct = new HashMap();
  25.     latestProduct.put("url""http://www.java2000.net");
  26.     latestProduct.put("name""Java世纪网");
  27.     root.put("latestProduct", latestProduct);
  28.     Template t = obj.getCfg().getTemplate("Test2.ftl");
  29.     Writer out = new OutputStreamWriter(new FileOutputStream("Test2.html"), "GBK");
  30.     t.process(root, out);
  31.     System.out.println("Successfull................");
  32.   }
  33. }


模板
  1. <html>
  2. <head>
  3.   <title>Welcome!</title>
  4. </head>
  5. <body>
  6.   <h1>Welcome ${user}!</h1>
  7.   <p>Our latest product:
  8.   <a href="${latestProduct.url}">${latestProduct.name}</a>!
  9. </body>
  10. </html> 


运行结果

  1. <html>
  2. <head>
  3.   <title>Welcome!</title>
  4. </head>
  5. <body>
  6.   <h1>Welcome java2000.net!</h1>
  7.   <p>Our latest product:
  8.   <a href="http://www.java2000.net">Java世纪网</a>!
  9. </body>
  10. </html> 


分析:
数据结构为
(root)
|
+- user = "java2000.net"
|
+- latestProduct
|
+- url = "http://www.java2000.net"
|
+- name = "Java世纪网"

我们使用嵌套的Map给其传递参数








<script type="text/javascript"> </script> <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值