Tuesday, September 18, 2012

Displaying Maven Project Version In Your Web Application

If you need to display the Maven pom project version of your web application on its web pages, the easiest way to do this is to use the standard Maven resource filtering functionality. Say we have the following main index.html page, and we'd like to place the pom version in the title of the page:
    <html>
    <head>
        <title>My Application — version ${project.version}</title>
    </head>
    <body>
        ...
    </body>
    </html>
We'll use a tweak of maven-war-plugin configuration to substitute the placeholder. This plugin is used anyway during the package phase, we only configure it to filter certain resources with the following code in the build/plugins section of the pom:

<build>
  
  <plugins>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.2</version>
            <configuration>
                <webResources>
                    <resource>
                        <directory>src/main/webapp</directory>
                        <filtering>false</filtering>
                        <excludes>
                            <exclude>**/*.html</exclude>
                        </excludes>
                    </resource>
                    <resource>
                        <directory>src/main/webapp</directory>
                        <filtering>true</filtering>
                        <includes>
                            <include>**/*.html</include>
                        </includes>
                    </resource>
                </webResources>
            </configuration>
        </plugin>

  </plugins>

</build>

With the maven-war-plugin configured as shown above, all the html files in the webapp directory will be filtered, i.e., ${project.version} and all other placeholders will be substituted for their actual values. All the rest of the resources will be copied without alteration. If your project uses jsp, xhtml or some sort of templating, you should configure the include/exclude file extensions respectively.

No comments:

Post a Comment