我正在尝试使用 ClasspathResourceLoader 来加载我的 *.vm 文件。我将它们放在/WEB-INF/templates 中,并将其添加到构建路径中。我的 web.xml 有:
<servlet>
<servlet-name>ServletVelocity</servlet-name>
<servlet-class>com.edw.servlet.VelocityServlet</servlet-class>
<init-param>
<param-name>org.apache.velocity.properties</param-name>
<param-value>/WEB-INF/velocity.properties</param-value>
</init-param>
</servlet>
velocity.properties 文件位于 WEB-INF 文件夹中。我需要的键/值是:
resource.loader = class
class.resource.loader.class = org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
但是,当我尝试时:
template = Velocity.getTemplate("index.vm");
我得到:
Exception caught: Unable to find resource 'index.vm'
我读到,如果我的 ResourceLoader 失败,则可能会发生这种情况,但我已在属性文件中将其指定为正确的,并且可以正常工作。
默认情况下,Velocity 使用位于 jar 内的velocity.properties 文件。如果我编辑那个(前面提到的两个键/值),一切都会正常。我的假设是 web.xml 中提到的 Velocity.properties 无法加载,但是当我运行 servlet 时,我可以在控制台中看到这一点:
INFO: Velocity [trace] Searching for properties at: /WEB-INF/velocity.properties
INFO: Velocity [debug] Configuring Velocity with properties at: /WEB-INF/velocity.properties
...
INFO: Velocity [debug] Initializing Velocity, Calling init()...
INFO: Velocity [debug] Default Properties File: org\apache\velocity\runtime\defaults\velocity.properties (???)
INFO: Velocity [debug] ResourceLoader instantiated: org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
INFO: Velocity [trace] ClasspathResourceLoader : initialization complete.
但是,如果我编辑velocity jar (org\apache\velocity\runtime\defaults\velocity.properties) 内的默认velocity.properties 文件,一切都会正常工作,我可以正常加载.vm:没有错误。
最佳答案
/WEB-INF/templates 中的文件不在类路径中,我不确定 Velocity,但 Spring 的 ClassPathResourceLoader 找不到该文件夹中的文件,您必须使用 Web 上下文资源然后加载器。
关于java - 通过 web.xml 的速度属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9080810/