找不到Velocity模板但是为什么?

时间:2015-06-22 07:52:33

标签: java java-ee velocity

我正在尝试用Velocity Template Engine做一个问候世界。这是我的代码:

package biz.tugay.app;

/* User: koray@tugay.biz Date: 22/06/15 Time: 10:36 */

import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
import org.apache.velocity.tools.view.VelocityViewServlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloTest extends VelocityViewServlet {

    @Override
    protected Template handleRequest
            (HttpServletRequest request, HttpServletResponse response, Context ctx) {
        Template template = null;
        try {
            ctx.put("name", "Velocity Test");
            template = Velocity.getTemplate("hello.vm");
        } catch( Exception e ) {
            System.err.println("Exception caught: " + e.getMessage());
        }
        return template;
    }
}

我会得到:

SEVERE: ResourceManager : unable to find resource 'hello.vm' in any resource loader.
Exception caught: Unable to find resource 'hello.vm'

我在WEB-INF中有一个 velocity.properties 文件:

resource.loader = class
class.resource.loader.class = org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader

hello.vm ,如果在 WEB-INF / classes 文件夹下找到,则显示如下:

hello $name

最后是web.xml:

<web-app>
    <servlet>
        <servlet-name>HelloTest</servlet-name>
        <servlet-class>biz.tugay.app.HelloTest</servlet-class>
        <init-param>
            <param-name>properties</param-name>
            <param-value>/WEB-INF/velocity.properties</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>HelloTest</servlet-name>
        <url-pattern>/HelloTest</url-pattern>
    </servlet-mapping>

</web-app>

我做错了什么?

1 个答案:

答案 0 :(得分:0)

好的,谢谢@Amos我让它的工作方式如下:

Velocity.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");                             
Velocity.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
ctx.put("name", "Velocity Test");                                                                
template = Velocity.getTemplate("hello.vm");