velocity的一个小问题,大家帮看看哇
直接贴代码吧。我在myeclipse下面新建了一个web项目,我的java代码是这样的。
package template;import java.io.StringWriter;import org.apache.velocity.Template;import org.apache.velocity.VelocityContext;import org.apache.velocity.app.VelocityEngine;public class HelloVelocity { public static void main(String[] args) { VelocityEngine ve=new VelocityEngine(); //初始化velocity模板引擎 ve.init(); Template template=ve.getTemplate("hellovelocity.vm"); //创建上下文,填充数据 VelocityContext context=new VelocityContext(); context.put("name", "world"); StringWriter writer=new StringWriter(); template.merge(context, writer); System.out.println(writer.toString()); } }
Hello $name, this is Velocity working!
2012-7-11 22:03:03 org.apache.velocity.runtime.log.JdkLogChute log严重: ResourceManager : unable to find resource 'hellovelocity.vm' in any resource loader.Exception in thread "main" org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'hellovelocity.vm' at org.apache.velocity.runtime.resource.ResourceManagerImpl.loadResource(ResourceManagerImpl.java:474) at org.apache.velocity.runtime.resource.ResourceManagerImpl.getResource(ResourceManagerImpl.java:352) at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1533) at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1514) at org.apache.velocity.app.VelocityEngine.getTemplate(VelocityEngine.java:373) at template.HelloVelocity.main(HelloVelocity.java:15)
Properties p = new Properties();p.setProperty("resource.loader", "class");p.setProperty("class.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");//设置资源加载器器为ClasspathResourceLoader,这段可以写到配置文件中...VelocityEngine ve = new VelocityEngine();ve.init(p);template = ve.getTemplate("/templates/hello.vm");