速度在获取模板时投掷NPE

kid*_*33t 5 java apache tomcat velocity jersey

我有一些在本地运行良好的代码,但是当我尝试在远程服务器上运行它时,它会抛出一个空指针异常.尝试从Velocity获取模板时会这样做.它第一次失败,每次失败.

有问题的代码是这样的:

    URL location = Thread.currentThread().getContextClassLoader().getResource("velocity.properties");
    String fullPath = location.getPath();
    log.debug("Path: " + fullPath);
    Velocity.init(fullPath);
    Template tmplt = Velocity.getTemplate( "template.html" );  //This line throws the error
Run Code Online (Sandbox Code Playgroud)

记录显示路径是正确的,我可以验证文件是否存在.

用于初始化velocity的属性文件包含:

resource.loader = file
file.resource.loader.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader
file.resource.loader.path=/var/lib/tomcat6/webapps/geoip/WEB-INF/templates/template.html
file.resource.loader.cache = true

input.encoding=UTF-8
output.encoding=UTF-8
Run Code Online (Sandbox Code Playgroud)

错误的堆栈跟踪如下所示:

SEVERE: Servlet.service() for servlet Jersey REST Service threw exception
java.lang.NullPointerException
at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1533)
at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1514)
at org.apache.velocity.runtime.RuntimeSingleton.getTemplate(RuntimeSingleton.java:299)
at org.apache.velocity.app.Velocity.getTemplate(Velocity.java:358)
at ca.company.ipservice.models.MyClass.toHTML(MyClass.java:48)
Run Code Online (Sandbox Code Playgroud)

我用Google搜索并搜索了StackOverflow,但我找不到任何答案.有任何想法吗?

A4L*_*A4L 6

该属性file.resource.loader.path应指向一个目录.尝试将其设置为目录/var/lib/tomcat6/webapps/geoip/WEB-INF/templates

file.resource.loader.path=/var/lib/tomcat6/webapps/geoip/WEB-INF/templates
Run Code Online (Sandbox Code Playgroud)

代替

file.resource.loader.path=/var/lib/tomcat6/webapps/geoip/WEB-INF/templates/template.html
Run Code Online (Sandbox Code Playgroud)

你似乎也有一个Web应用程序.在这种情况下,最好是使用WebappResourceLoader速度的工具

resource.loader = webapp
webapp.resource.loader.class = org.apache.velocity.tools.view.WebappResourceLoader
webapp.resource.loader.path = templates
webapp.resource.loader.cache = false
Run Code Online (Sandbox Code Playgroud)

并在初始化之前设置servlet context属性

VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.setApplicationAttribute("javax.servlet.ServletContext", context);
Run Code Online (Sandbox Code Playgroud)

这里contextServletContext.该目录templates应位于您的Web根目录中,因此位于相同的位置WEB-INF.

编辑

如果您将应用程序打包到war文件中并将其部署到不解压缩的应用服务器上,以便您可以直接访问文件系统,那么您可以考虑使用ClasspathResourceLoader.为此,您必须将模板打包到一个自己的jar文件中WEb-INF/lib.for的参数getTemplate(...)必须遵循检索位于类路径中的资源的规则(请参阅ClassLoader#getResourceAsStream).

resource.loader = classpath
classpath.resource.loader.description = Velocity Classpath Resource Loader
classpath.resource.loader.class = org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
classpath.resource.loader.cache = false
Run Code Online (Sandbox Code Playgroud)

在这里,您可以找到有关如何加载模板(也称为资源)的更多信息.