如何读取在apache tomcat中运行的webapp的清单文件?

Nik*_*man 46 java tomcat jar manifest

我有一个包含清单文件的webapp,我在其中编写了一个ant构建任务期间我的应用程序的当前版本.清单文件是正确创建的,但是当我尝试在运行时读取它时,我会得到一些奇怪的副作用.我在清单中阅读的代码是这样的:

    InputStream manifestStream = Thread.currentThread()
                                 .getContextClassLoader()
                                 .getResourceAsStream("META-INFFFF/MANIFEST.MF");
    try {
        Manifest manifest = new Manifest(manifestStream);
        Attributes attributes = manifest.getMainAttributes();
        String impVersion = attributes.getValue("Implementation-Version");
        mVersionString = impVersion;
    }
    catch(IOException ex) {
        logger.warn("Error while reading version: " + ex.getMessage());
    }
Run Code Online (Sandbox Code Playgroud)

当我将eclipse附加到tomcat时,我看到上面的代码有效,但它似乎得到了一个不同于我预期的清单文件,我可以告诉它,因为ant版本和构建时间戳都是不同的.然后,我在那里放了"META-INFFFF",上面的代码仍然有效!这意味着我正在阅读其他一些清单,而不是我的清单.我也试过了

this.getClass().getClassLoader().getResourceAsStream(...)
Run Code Online (Sandbox Code Playgroud)

但结果是一样的.从tomcat中运行的webapp内部读取清单文件的正确方法是什么?

编辑:感谢您的建议到目前为止.另外,我应该注意到我正在运行tomcat独立; 我从命令行启动它,然后附加到Eclipse调试器中正在运行的实例.这不应该有所作为,不是吗?

Pas*_*ent 90

也许你的副作用来自这样一个事实,即几乎所有的罐子都包含一个MANIFEST.MF而且你找不到合适的罐子.要从webapp读取MANIFEST.MF,我会说:

ServletContext application = getServletConfig().getServletContext();
InputStream inputStream = application.getResourceAsStream("/META-INF/MANIFEST.MF");
Manifest manifest = new Manifest(inputStream);
Run Code Online (Sandbox Code Playgroud)

请注意,从Eclipse运行Tomcat与单独运行Tomcat不同,因为Eclipse使用类加载器.

  • +1用于提供实际工作的实际代码. (2认同)

jav*_*ude 11

有点晚了,但这对我有用(Glassfish中的web应用)

Properties prop = new Properties();
prop.load(getServletContext().getResourceAsStream("/META-INF/MANIFEST.MF"));
System.out.println("All attributes:" + prop.stringPropertyNames());
System.out.println(prop.getProperty("{whatever attribute you want}"));
Run Code Online (Sandbox Code Playgroud)

  • 注意:按照[RFC-822](http://www.ietf.org/rfc/rfc0822.txt),你会发现使用`Properties`会出现问题,因为长值会在更多行中被破坏.用户`Manifest`类. (9认同)

dav*_* a. 1

不知道阅读它的“官方”方式,但是如果 MANIFEST.MF 无法作为资源正确加载,那么尝试从某个 Web 路径上的“ServletContext.getRealPath()”派生其路径如何在您的应用程序中定义?

我想到的另一个解决方案是在构建期间由 ant 将应用程序版本写入其他位置(WEB-INF/类中的属性文件)。