免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1430 | 回复: 0
打印 上一主题 下一主题

在独立的应用程序中使用 Velocity 模板引擎 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-05-10 13:49 |只看该作者 |倒序浏览
[代码] example2.vm
Hello from $name in the $project project.


[代码] java代码
  1. import java.io.StringWriter;
  2. import java.util.Properties;
  3. import org.apache.velocity.app.Velocity;
  4. import org.apache.velocity.VelocityContext;

  5. import org.apache.velocity.exception.ParseErrorException;
  6. import org.apache.velocity.exception.MethodInvocationException;

  7. public class Example2
  8. {
  9.     public static void main( String args[] )
  10.     {
  11.         // first, we init the runtime engine.  Defaults are fine.
  12.         
  13.         try
  14.         {
  15.             Velocity.init();
  16.         }
  17.         catch(Exception e)
  18.         {
  19.             System.out.println("Problem initializing Velocity : " + e );
  20.             return;
  21.         }

  22.         // lets make a Context and put data into it

  23.         VelocityContext context = new VelocityContext();

  24.         context.put("name", "Velocity");
  25.         context.put("project", "Jakarta");
  26.         
  27.         // lets render a template

  28.         StringWriter w = new StringWriter();

  29.         try
  30.         {
  31.             Velocity.mergeTemplate("./src/example2.vm", context, w );
  32.         }
  33.         catch (Exception e )
  34.         {
  35.             System.out.println("Problem merging template : " + e );
  36.         }

  37.         System.out.println(" template : " + w );

  38.         String s = "We are using $project $name to render this.";
  39.         w = new StringWriter();

  40.         try
  41.         {
  42.             Velocity.evaluate( context, w, "mystring", s );
  43.         }
  44.         catch( ParseErrorException pee )
  45.         {
  46.             System.out.println("ParseErrorException : " + pee );
  47.         }
  48.         catch( MethodInvocationException mee )
  49.         {
  50.             System.out.println("MethodInvocationException : " + mee );
  51.         }
  52.         catch( Exception e )
  53.         {
  54.             System.out.println("Exception : " + e );
  55.         }

  56.         System.out.println(" string : " + w );
  57.     }
  58. }
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP