apache velocity资源未找到异常,即使模板文件位于同一目录中

时间:2014-02-27 01:05:25

标签: java templates velocity

我已经了解了速度作为模板引擎,并在我的代码片段中尝试了。

package myproj.templating.velocity;

import java.io.StringWriter;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

public class velocityTest {

    public static void main (String args[]) {

        VelocityEngine ve = new VelocityEngine();
        ve.init();

        VelocityContext context = new VelocityContext();

        context.put( "name", new String("Velocity") );

        Template template = null;

        try
        {
           template = ve.getTemplate("mytemplate.vm");
        }
        catch (ResourceNotFoundException rne) {
            rne.printStackTrace();
        }
        catch ( ParseErrorException pee )

        {
          // syntax error: problem parsing the template
            pee.printStackTrace();
        }
        catch( MethodInvocationException mie )
        {
          // something invoked in the template
          // threw an exception
            mie.printStackTrace();
        }
        catch( Exception e )
        { e.printStackTrace();}

        StringWriter sw = new StringWriter();

        template.merge( context, sw );

        System.out.println("result= " + sw.toString());
    }
}

mytemplate.vm文件与此代码位于同一目录中,我已多次检查拼写。但我仍然得到ResourceNotFound异常。什么可能是错的?我已经尝试过关于stackflow的建议来添加文件路径和什么不是但仍然得到相同的异常。

1 个答案:

答案 0 :(得分:1)

按照设置完成了这个伎俩。

Properties p = new Properties();
 p.setProperty("resource.loader","file");
 p.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
 p.setProperty("file.resource.loader.path","/actual/full/path/here");           
 p.setProperty("file.resource.loader.cache", "false");
 p.setProperty("file.resource.loader.modificationCheckInterval", "0");

ve.init(p);