FreeMarker最简单的例子(1)

一、通过文件来创建模版对象,并执行插值操作

文件结构为:

 

Test.Java中的代码为:

 

[java]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. package com.abc;  
  2.   
  3.    
  4.   
  5. import freemarker.template.Configuration;   
  6.   
  7. import freemarker.template.Template;   
  8.   
  9. import java.io.File;   
  10.   
  11. import java.io.OutputStreamWriter;   
  12.   
  13. import java.util.HashMap;   
  14.   
  15. import java.util.Map;   
  16.   
  17.    
  18.   
  19. public class Test {   
  20.   
  21.     public static void main(String[] args) throws Exception {   
  22.   
  23.         //创建一个Configuration实例   
  24.   
  25.         final Configuration cfg;     
  26.   
  27.         cfg = new Configuration();   
  28.   
  29.         //设置FreeMarker的模版文件夹位置   
  30.   
  31.         cfg.setDirectoryForTemplateLoading(new File("D:\\workspace\\freemarkertest\\src\\com\\abc"));  
  32.   
  33.         Map<String, String> map = new HashMap<String, String>();   
  34.   
  35.         map.put("user", "Zheng");  
  36.   
  37.         map.put("website", "金额宝");   
  38.   
  39.         map.put("url", "http://www.jebao.net/");   
  40.   
  41.         //创建模版对象   
  42.   
  43.         Template t = cfg.getTemplate("test.ftl");   
  44.   
  45.         //在模版上执行插值操作,并输出到制定的输出流中   
  46.   
  47.         t.process(map, new OutputStreamWriter(System.out));   
  48.   
  49.     }   
  50.   
  51. }  

 

 

Test.ftl中的代码为:

 

[html]  view plain  copy
 
 在CODE上查看代码片派生到我的代码片
  1. <html>   
  2.   
  3. <head>   
  4.   
  5.     <title>Welcome!</title>   
  6.   
  7. </head>   
  8.   
  9. <body>   
  10.   
  11.     <h1>Welcome ${user}!</h1>   
  12.   
  13.     <p>Our latest product:   
  14.   
  15.     <href="${url}">${website}</a>!   
  16.   
  17. </body>   
  18.   
  19. </html>   
  20.   
  21.    
  22.   
  23. 尊敬的用户你好!  
  24.   
  25. 用户名:${user}  
  26.   
  27. URL:    ${url}  
  28.   
  29. 网站:  ${website}  

 

 

运行结果为:

</head>

<body>

    <h1>Welcome Zheng!</h1>

    <p>Our latest product:

    <ahref="http://www.jebao.NET/">金额宝</a>!

</body>

</html>

 

尊敬的用户你好!

用户名:Zheng

URL:   http://www.jebao.Net/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值