首页 > 解决方案 > 速度模板文件资源加载器不工作

问题描述

面对一些奇怪的问题,像这样设置 Velocity Engine。

 Properties properties = new Properties();
    properties.setProperty(RuntimeConstants.EVENTHANDLER_INCLUDE,IncludeRelativePath.class.getName());

    properties.setProperty(RuntimeConstants.RESOURCE_LOADER, "file");
    properties.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    File f = new File(".");
    LOGGER.info("Base class path : {}",f.getCanonicalPath());
    //Objects.requireNonNull(resource);
    properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH,f.getCanonicalPath());
    VelocityEngine velocityEngine = new VelocityEngine();
    velocityEngine.init(properties);
    return velocityEngine;

然后我试图获取使用创建的文件:

PrintWriter out = new PrintWriter(templateName+".vm");
        out.println(fileContentStr);
        out.close();

像这样 :

Template t = this.getEngine().getTemplate(  fileName + ".vm");

这给了我 ResourceNotFoundException。它在我的本地工作。我没有在任何地方对路径进行硬编码。无法理解为什么它不起作用。请有人可以在这里帮助我。尝试所有排列组合后我被卡住了。

动机:我只需要能够从项目目录中读取 VM 文件并创建一个。

标签: javavelocity

解决方案


如果您确定工作目录在构建模板和读取模板之间没有变化,那么您不需要在初始化 Velocity 之前设置任何属性:

  • 您不需要,IncludeRelativePath因为它的目的是让#include() 和#parse() 在与当前模板相同的目录中查找模板。它不适用于您的用例。
  • 您不需要设置file资源加载器,因为它是默认设置。
  • 您当然不需要设置classpath资源加载器的类,因为您甚至没有使用它
  • 您不需要设置文件资源加载器路径,因为它默认为“.”。

我不知道为什么您的代码在本地工作而不是在生产环境中工作。也许工作目录已更改。也许变量templateNamefileName不一致。也许模板在编写之前就被要求了。环境之间是否有任何重大差异?有什么安全问题吗?操作系统是一样的吗?正如 soorapadman 所指出的,这可能是 linux 和 Windows 之间区分大小写的问题。

以下代码应该在任何地方都可以使用:

VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.init();
PrintWriter out = new PrintWriter("test.vm");
out.println("hello");
out.close();
Template template = velocityEngine.getTemplate("test.vm");

推荐阅读