velocity的HelloWord

1、目录:


2、test.vm内容:

  1. <html>
  2. <body>

  3. #set($foo ="velocity")

  4. Hello $foo world;

  5. My name is $myname

  6. Your name is $yourname

  7. </body>
  8. </html>

3、velocity.properties内容:

input.encoding = UTF-8
file.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader

4、TestTemplateTheory.java内容:

  1. public static void main(String[] args) throws IOException {
  2. Properties properties=new Properties();
  3. /**方法一:加载classpath下的vm,即WEB-INF\classes*/
  4. properties.put("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
  5. /**方式二:根据绝对路径加载,vm文件置于硬盘某分区中,如:d://tree.vm*/
  6. //properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, "d://");
  7. /**方法三:通过Class的方法加载velocity.properties属性文件*/
  8. /*Class方法getResourceAsStream(String path):path 不以’/'开头时默认是从此类所在的包下取资源,以’/'开头则是从
  9.   ClassPath根下获取。其只是通过path构造一个绝对路径,最终还是由ClassLoader获取资源。
  10.  如果path中有/那么从开始都有/,如:/com/velocity/file.txt。
  11. */
  12. //properties.load(this.getClass().getResourceAsStream("velocity.properties"));
  13. //properties.load(new TestTemplateTheory().getClass().getResourceAsStream("/com/velocity/test/velocity.properties"));
  14. /**方法四:Class.getClassLoader.getResourceAsStream(String path) :默认则是从ClassPath根下获取,path不能以’/'开头,最终是由
  15.                    ClassLoader获取资源。形式如:com/velocity/file.txt,com前不能有/。  */
  16. //properties.load(new TestTemplateTheory().getClass().getClassLoader().getResourceAsStream("com/velocity/test/velocity.properties"));
  17. // 初始化velocity引擎
  18. VelocityEngine ve = new VelocityEngine();
  19. ve.init(properties);
  20. // 获取模板
  21. Template template = ve.getTemplate("template/test.vm");


  22. // 填充数据
  23. VelocityContext velocityContext = new VelocityContext();
  24. velocityContext.put("myname", "姚明");
  25. velocityContext.put("yourname", "麦迪");


  26. // 合并数据
  27. StringWriter writer = new StringWriter();
  28. template.merge(velocityContext, writer);


  29. // 显示
  30. System.out.println(writer.toString());
  31. System.out.println(template);
  32. }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值