velocity中加载模板文件的方式

velocity有多中种方式供我们去加载我们自定义的模板文件,下面详细的介绍使用的方法。

1.1.1. 加载classpath目录下的模板文件

使用classpath方式加载,是我们经常用到的一种方式,因为我们的项目可能是web项目,使用这种方式加载我们类加载器跟路径中的模板文件,具体的使用如下所示:

程序的结构如下图所示:

 

shareniu.vm中我们定义了两个变量name,author模板的内容如下所示:

$name,

$author

程序如下所示:

Properties p = new Properties();
p.put("file.resource.loader.class",
"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
Velocity.init(p);
String templateFile="shareniu.vm";
Template template = Velocity.getTemplate(templateFile);
VelocityContext context = new VelocityContext();
        context.put("name", "shareniu.vm");
        context.put("author", "shareniu");
        StringWriter writer = new StringWriter();
        template.merge(context, writer);
        System.out.println(writer);


输出的程序如下:

shareniu.vm,

shareniu

大功告成,程序如期的输出我们定义的变量信息,并且进行了替换。

1.1.2. 根据绝对路径加载,模板文件置于硬盘中

有的时候,我们的项目不是一个web项目,所以,我们可以使用绝对路径加载的方式进行操作。模板还是第一种方式的模板。

具体的使用如下所示:

Properties p = new Properties();
p.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, "d://");
Velocity.init(p);
Template template =Velocity.getTemplate("shareniu.vm");
VelocityContext context = new VelocityContext();
        context.put("name", "shareniu.vm");
        context.put("author", "shareniu");
        StringWriter writer = new StringWriter();
        template.merge(context, writer);
        System.out.println(writer);


输出的程序如下:

shareniu.vm,

shareniu

大功告成,程序如期的输出我们定义的变量信息,并且进行了替换。

 

总结:

第一种方式使用的场景是web项目,或者不依赖操作系统具体的位置,依赖项目的位置。第二种使用的场景就是位置是固定的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值