2012-01-31 42 views
1

我想使用ClasspathResourceLoader加載我的* .vm文件。我將它們放入/ WEB-INF /模板中,並將其添加到構建路徑中。我的web.xml有:速度屬性文件通過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' 

我讀過,如果我的資源加載失敗,這可能發生,但我已經在屬性文件中指定它是正確的,它的工作原理。

默認情況下,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.properties速度jar裏面的文件(org \ apache \ velocity \ runtime \ defaults \ velocity.properties),一切正常,我可以加載.vm好的:沒有錯誤。

+0

請將您的答案添加爲「答案」 – nidhin 2012-01-31 14:38:46

回答

1

文件中/WEB-INF /模板不在類路徑中,我不知道,但速度Spring的ClassPathResourceLoader不能該文件夾中查找文件,你必須使用一個Web上下文資源加載器即可。

+0

我已將/ WEB-INF /模板添加到構建路徑(classpath?)中,如apache網站所述。 – Buffalo 2012-02-01 09:40:56

1

當你調用Velocity.doanything時,你要求Velocity單例做它。您的速度屬性正在配置VelocityServlet,而不是Velocity單件。

查看VelocityTools項目中的一些示例servlet應用程序。在那裏你會發現一個未被棄用的優秀servlet,以及在servlet環境中如何使用Velocity的一些例子。