java - 速度模板文件资源加载器不工作
问题描述
面对一些奇怪的问题,像这样设置 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 文件并创建一个。
解决方案
如果您确定工作目录在构建模板和读取模板之间没有变化,那么您不需要在初始化 Velocity 之前设置任何属性:
- 您不需要,
IncludeRelativePath
因为它的目的是让#include() 和#parse() 在与当前模板相同的目录中查找模板。它不适用于您的用例。 - 您不需要设置
file
资源加载器,因为它是默认设置。 - 您当然不需要设置
classpath
资源加载器的类,因为您甚至没有使用它 - 您不需要设置文件资源加载器路径,因为它默认为“.”。
我不知道为什么您的代码在本地工作而不是在生产环境中工作。也许工作目录已更改。也许变量templateName
和fileName
不一致。也许模板在编写之前就被要求了。环境之间是否有任何重大差异?有什么安全问题吗?操作系统是一样的吗?正如 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");
推荐阅读
- python - 如何在 Python 中对 Pandas DataFrame 上的循环进行矢量化?
- javascript - 如何使用重定向将道具传递给路由
- javascript - 如何在滑块中添加自动滚动
- amazon-cognito - 为了将 { cognito-identity.amazonaws.com:aud } 的价值传递给 IAM 角色,我应该如何以及传递什么?
- java - 如何通过 JSch 以编程方式处理 Kerberos 提示
- ruby-on-rails - Action Mailer 'undefined method `[]' for nil:NilClass'
- python - ValueError:找到暗淡为 3 的数组。估计器预期 <= 2。>>>
- spring-data - Apache Ignite cache data is not getting replicated on every cluster node, when cache mode set to REPLICATED
- jmeter - How to remove array present in Json in jmeter
- postgresql - Stimulsoft Report Unicode Character from Postgresql