【问题标题】:Loading Velocity Templates from nested JARs从嵌套 JAR 加载 Velocity 模板
【发布时间】:2014-05-08 19:54:32
【问题描述】:

我有一个打包在 onejar 中的应用程序,它使用 Velocity 进行模板化。

在我的 Maven 项目设置中,我在 $base/src/main/resources/template.html 中有一个文件。当应用程序被打包为 onejar 时,生成的 onejar 在其中包含一个嵌套的 jar(在 main/my-jar.jar 下)。该 jar 又将 template.html 文件打包在其根目录下。 (显然是 maven 将其从 src/main/resources 复制到包的根目录中)

我想将该模板作为资源加载到 Velocity 中。我读过我需要使用 ClassPathResourceLoader 来执行此操作,所以我的代码如下所示:

    VelocityEngine ve = new VelocityEngine();
    ve.setApplicationAttribute("resource.loader", "class");

    ve.setApplicationAttribute("class.resource.loader.class", 
                               org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader.class);

    ve.init();
    Template t = ve.getTemplate("template.html");

这每次都会失败,除了 Velocity 的资源加载器都找不到该文件。

我有两个问题 - 首先,这是否是配置 ClasspathResourceLoader 使用的正确方法?其次,如果配置正确,我将指定什么路径以便可以在该内部嵌套 jar 中找到 template.html?

【问题讨论】:

    标签: java classpath velocity onejar


    【解决方案1】:

    经过大量的挖掘,我终于找到了答案。

    ClasspathResourceLoader的使用代码如下:

    VelocityEngine ve = new VelocityEngine();
    
    ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); 
    ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    
    ve.init();
    

    其次,很多人告诉我,在嵌套的 jar 中,标准的类路径加载器甚至不应该能够找到 template.html 文件。有人告诉我,需要一些花哨的第三方类加载器。 OneJar 提供了这样一个花哨的加载器。一旦我得到正确的代码以使用 ClasspathResourceLoader,事情似乎就解决了。

    要记住的是,“/”是相对于类路径根的。因此,当 $base/src/main/resources/template.html 在解压后的 JAR 的根目录中重新打包为 template.html 时,这意味着 /template.html 是正确的加载资源路径。

    /template.html 的路径当然是相对于嵌套的内部 JAR。类加载器(无论是标准的还是 OneJar 的)如何在外 jar 和内 jar 的 / 之间没有混淆,我不知道。

    【讨论】:

      【解决方案2】:

      使用 / 作为相对路径指定你的 template.html 所在的路径

      并使用setProperty,如下所示

      VelocityEngine ve = new VelocityEngine();
                  ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
                  ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
      
                  ve.init();
      
                  final String templatePath = "/" + template + ".html";
      
      
                  Template template = ve.getTemplate(templatePath, "UTF-8");
      

      【讨论】:

        猜你喜欢
        • 2021-06-14
        • 1970-01-01
        • 2015-01-03
        • 2012-01-26
        • 2018-08-31
        • 1970-01-01
        • 2017-01-24
        • 1970-01-01
        • 2011-04-26
        相关资源
        最近更新 更多