How to read MANIFEST.MF inside WAR application?

前端 未结 4 1515
执笔经年
执笔经年 2021-02-04 07:07

I would like to read MANIFEST.MF of my WAR application. How can I find its file name?

4条回答
  •  南笙
    南笙 (楼主)
    2021-02-04 07:37

    I did some researches to find the right solution for me. Mainly thanks to BalusC but also others I cannot remember now because I went deeply in many sources. I have a web application running on Weblogic 12c (12.2.1.4) version. First I had to say maven to add information in MANIFEST.MF, adding the following in plugins section of POM file

     
        maven-war-plugin
        2.2
        
          
             
             true
              true
            
          
        
      
    

    You can find the version of maven plugin looking at the console in the package goal.

    Then I've mainly followed the BalusC direction in the post Using special auto start servlet to initialize on startup and share application data

    Before registering the class in the servlet context in the contextInitialized method

     @Override public void contextInitialized(ServletContextEvent servletContextEvent)
    

    I've put my business logic to retrieve information from the manifest, like the following

        @Override public void contextInitialized(ServletContextEvent servletContextEvent) {
            logger.info("context initialized - reading MANIFEST.MF infos");
            StringBuilder welcomeStrBuild;
            welcomeStrBuild = new StringBuilder("version");
            try (InputStream inputStream = servletContextEvent.getServletContext().getResourceAsStream("/META-INF/MANIFEST.MF")) {
                Properties prop = new Properties();
                prop.load(inputStream);
                welcomeStrBuild.append(prop.getProperty("Implementation-Version", "n/a"));
            } catch (Exception e) {
                logger.info("Unable to extract info from MANIFEST.MF");
                welcomeStrBuild.append("Unable to extract info from MANIFEST.MF");
            }
            infoProject = welcomeStrBuild.toString();
            servletContextEvent.getServletContext().setAttribute("config", this);
    }
    

    You can of course read the content of the manifest using the Java Manifest class, instead of using Properties class.

    The main points of the solution are the two:

    • add the information to the manifest using the maven war goal
    • read the information at right moment and from the right WAR, because if you are not using the correct approach you end in reading the manifest from the classloader or other jars

提交回复
热议问题