如何在jsp页面中获取maven项目版本号?

时间:2009-10-06 10:40:30

标签: java maven-2

我正在研究由maven2管理的java Web应用程序。我们不时做了一些更改,并希望做新版本,当然还有新版本号。在主页(jsp)中,有像

这样的文本
<b>version:</b> 2.3.3... 

是否有可能,每次我发布新版本时,我只更改pom.xml中的<version/>,jsp中的版本号可以由此maven $ {project.version}自动填充?

我尝试了maven个人资料,但似乎没有用。

任何想法?

谢谢。

11 个答案:

答案 0 :(得分:30)

您可以使用project filtering处理JSP,因为它已复制到目标位置。如果使用${project.version}指定JSP,并且将包含文件夹指定为过滤器位置,则应在打包时将值替换为JSP。

例如,将其添加到POM可以过滤src / main / resources:

<resources>
  <resource>
    <directory>src/main/resources</directory>
    <filtering>true</filtering>
  </resource>
</resources>

更新:对于war包装,您可能需要配置war插件来进行过滤。有关详细信息和示例,请参阅war-plugin documentationFiltering部分。

基本上这个过程是一样的,但它是在war插件下面定义的,所以你有这样的东西:

<plugins>
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.0</version>
    <configuration>
      <webResources>
        <resource>
          <directory>src/main/resources</directory>
          <filtering>true</filtering>
        </resource>
      </webResources>
    </configuration>
  </plugin>
</plugins>

答案 1 :(得分:11)

这可能是愚蠢的,但我会使用this example中的.properties文件,而不是直接过滤JSP。

答案 2 :(得分:2)

这篇文章已经创建了一段时间,但我希望它会有所帮助。它将获得从Maven生成的属性:

<%@ page import="java.util.*"%>
<%
    java.io.InputStream inputStream = getServletContext().getResourceAsStream("/META-INF/maven/com.filhetallard.fam.ged/famdox/pom.properties");
    Properties mavenProperties= new Properties();
    mavenProperties.load(inputStream );
    String version = (String) mavenProperties.get("version");
    String name = (String) mavenProperties.get("artifactId");

%><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
<head> 
    <title>Application <%= name %> v<%= version %></title>

不幸的是,有一些缺点:

  • 您必须明确地在代码中编写groupId和artifactId
  • 如果您将web-app直接从目标/部署到服务器,它将无法找到该文件,因为在打包之前,该文件位于maven-archiver目录中,而不是META-INF中。

问候。

答案 3 :(得分:2)

我想做同样的事情,但我对任何现有的解决方案都不满意,包括使用Maven过滤方法,这是好的,但我试图在构建过程中不再修改现有的代码文件所以我把这种方法排除在外,虽然这是一种合理的方法。

我将Maven项目版本放入JSP文件的方式是基于与here类似的方法,除了我没有创建Version.java文件,而是让Maven编写版本输出到属性文件,例如“version.properties”,如下所示:

version.properties:

app.version = 0.1

并让Maven将它放在类路径上,例如,在src / main / resources中,如下所示:

    <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.7</version>
    <executions>
          <execution>
            <goals>
              <goal>run</goal>
            </goals>
            <phase>generate-sources</phase>
            <configuration>
            <!-- Idea from link: http://stackoverflow.com/questions/2469922/generate-a-version-java-file-in-maven -->
              <target>
                <property name="resources.dir" value="${project.build.sourceDirectory}/../resources" />
                <property name="version.filename" value="version.properties" />
                <property name="buildtime" value="${maven.build.timestamp}" />
                <echo message="Writing project version string to ${resources.dir}/${version.filename} ..." />
                <echo file="${resources.dir}/${version.filename}" message="app.version = ${project.version}${line.separator}" />
              </target>
            </configuration>
          </execution>
        </executions>
  </plugin>

此外,如果您使用的是Spring Framework 3.x +,那么您可以添加以下配置来加载version.properties中的属性(如果存在),否则只显示“v0.0”或其他:

@Configuration
@EnableWebMvc
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class WebHomeConfig extends WebMvcConfigurerAdapter implements
    ApplicationContextAware {

  private ApplicationContext _appContext;


  /*
   * (non-Javadoc)
   * 
   * @see
   * org.springframework.context.ApplicationContextAware#setApplicationContext
   * (org.springframework.context.ApplicationContext)
   */
  @Override
  public void setApplicationContext(ApplicationContext appContext)
      throws BeansException {
    _appContext = appContext;
  }

  @Bean
  public ViewResolver getViewResolver() {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix(".jsp");
    resolver.getAttributesMap().put("appVersion", appVersion);
    return resolver;
  }


  /**
   * Since we don't have any controller logic, simpler to just define
   * controller for page using View Controller. Note: had to extend
   * WebMvcConfigurerAdapter to get this functionality
   * 
   * @param registry
   */
  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("home");
  }

  /**
   * The application version.
   */
  @Value("${app.version:0.0}")
  protected String appVersion;

  @Bean
  public static PropertySourcesPlaceholderConfigurer configurer() {
    PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();

    configurer.setIgnoreResourceNotFound(true);
    configurer.setLocations(new Resource[] {
        new ClassPathResource("version.properties")});
    return configurer;
  }

}

最后,在你的/WEB-INF/views/home.jsp中你可以得到类似的内容:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Service Status</title>
    </head>
    <body>
        <h1>Service API</h1>
        <p>The service is up and running! (v${appVersion})</p>
    </body>
</html>

这当然会呈现为:

  

该服务已启动并正在运行! (V0.1)

注意:如果您不使用JavaConfig类来配置Spring Framework,那么您可以使用Spring XML配置执行相同的操作。

答案 4 :(得分:2)

使用maven-replacer-plugin

在pom.xml中包含插件,如下所示:

    <plugin>
        <groupId>com.google.code.maven-replacer-plugin</groupId>
        <artifactId>replacer</artifactId>
        <version>(version)</version>
        <executions>
            <execution>
                <phase>prepare-package</phase>
                <goals>
                    <goal>replace</goal>
                </goals>                    
            </execution>
        </executions>
        <configuration>
            <ignoreMissingFile>true</ignoreMissingFile>
            <file>target/someapp/jsp/helloWorld.jsp</file>
            <outputFile>
                target/someapp/jsp/helloWorld-updated.jsp
            </outputFile>
            <regex>false</regex>
            <token>$BUILD_NUMBER$</token>
            <value>${buildNumber}</value>
        </configuration>
    </plugin>

现在指定文件中任何位置都有令牌$BUILD_NUMBER$,令牌将被替换。

答案 5 :(得分:1)

我使用这个插件,

http://code.google.com/p/maven-substitute-plugin/

你可以在Java中做这样的事情,

   public final static String projectVersion = "@PROJECT_VERSION@";

将这个值传递给JSP很简单。

答案 6 :(得分:1)

父pom.xml:

<properties>
        <!-- in my case injected by jenkins build job -->
        <build.version>dev</build.version>
        <build.branch>local</build.branch>
        <build.revision />
 </properties>

资源过滤(占位符在此处由pom-property值替换)

<resources>
   <resource>
       <directory>src/main/resources</directory>
       <includes>
            <include>conf/version.properties</include>
       </includes>
       <filtering>true</filtering>
   </resource>
</resources>

webContext.xml中的Bean和属性占位符配置:

<context:property-placeholder location="classpath:conf/version.properties"/>

    <bean id="buildVersion" class="de.your.package.cfg.BuildVersion">
        <property name="buildBranch" value="${build_branch}"/>
        <property name="buildVersion" value="${build_version}"/>
        <property name="buildRevision" value="${build_revision}"/>
    </bean>

你的bean看起来像这样

@Component
public class BuildVersion {

    private String buildBranch;
    private String buildVersion;
    private String buildRevision;

    public String getBuildRevision() {
        return buildRevision;
    }

    public void setBuildRevision(String buildRevision) {
        this.buildRevision = buildRevision;
    }

    public String getBuildVersion() {
        return buildVersion;
    }

    public void setBuildVersion(String buildVersion) {
        this.buildVersion = buildVersion;
    }

    public String getBuildBranch() {
        return buildBranch;
    }

    public void setBuildBranch(String buildBranch) {
        this.buildBranch = buildBranch;
    }

}

这是你的JSP片段:

<%@ page language="java"
   import="java.util.*,
        org.springframework.context.ApplicationContext,
    org.springframework.web.context.support.WebApplicationContextUtils,
         de.smava.kredithai.cfg.BuildVersion" %>
<%
    ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(pageContext.getServletContext());
    BuildVersion buildVersion = (BuildVersion) applicationContext.getBean("buildVersion");

    String branch = (String) buildVersion.getBuildBranch();
    String version = (String) buildVersion.getBuildVersion();
    String revision = (String) buildVersion.getBuildRevision();

    if (request.getParameter("branch") != null){
        out.println(branch);
    } else if (request.getParameter("version") != null){
        out.println(version);
    } else if (request.getParameter("link") != null){
        out.println("<a href=\"http://your_server_url"+branch+"/"+version+"\" >" + branch + " build " + version + "</a>");
    } else {
        out.println(branch + " build " + version + " rev. " + revision);
    }
%>

答案 7 :(得分:1)

我会将.jsp的值交给

String version = getClass().getPackage().getImplementationVersion();
例如,

看起来像1.0.0-SNAPSHOT

如果您只是获取空值,则可能需要将类路径添加到war的清单

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.5</version>
    <configuration>
        <archive>
            <manifest>
                <addClasspath>true</addClasspath>
            </manifest>
        </archive>
    </configuration>
</plugin>

让类加载器拿起它。

答案 8 :(得分:0)

http://mojo.codehaus.org/jspc/jspc-maven-plugin/usage.html

它说明了这一点:
非WAR项目

您也可以将此插件用于非战争项目,例如验证JSP。它们将被编译,但不包含在您的最终工件中,并且不会生成或修改任何web.xml文件。

如果您只想验证和编译JSP而不实际包含war项目中生成的代码,您还可以使用includeInProject参数设置为false。

答案 9 :(得分:0)

您可以在JSP文件中使用它(在我的示例中为template.jsp)

<head>
<meta name="Historia Social Unica version:${version}" />

然后在项目的pom.xml中,你必须激活过滤:

<resources>
  <resource>
    <includes>
       <include>template.jsp</include>
    </includes>
    <directory>src/main/webapp/jsp/template</directory>
    <targetPath>jsp/template/</targetPath>
    <filtering>true</filtering>
  </resource>
 </resources>
</build>

您获取的JSP已替换变量版本。

答案 10 :(得分:0)

有很多传递值的方法(如这些注释中所述)。另一种方法(各有利弊)是将参数从POM文件添加到清单中:

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.6</version>
            <configuration>
                <archive>
                    <manifestEntries>
                        <Build-Version>${project.version}</Build-Version>
                        <Build-Date>${buildDateTime}</Build-Date>
                        <Build-Number>${buildNumber}</Build-Number>
                        <Build-Revision>${buildRevision}</Build-Revision>
                    </manifestEntries>
                </archive>
            </configuration>
        </plugin>

,然后打开并阅读清单以在配置过程中设置单例bean,或使用以下命令将其直接导入JSP:

<%
    String buildVersion;
    String buildDate;
    String buildRevision;
    String buildNumber;
    Attributes attributes;
    String version = "";
    InputStream in = null;

    // Get manifest attributes
    try {
        Manifest manifest;

        in = pageContext.getServletContext().getResourceAsStream("/META-INF/MANIFEST.MF");
        manifest = new Manifest(in);
        attributes = manifest.getMainAttributes();
    } catch (Exception ex) {
        attributes = new Attributes();
        attributes.put(new Attributes.Name("Build-Version"), "None (Inplace Deployment)");
    } finally {
        if (in != null) {
            in.close();
        }
    }
    buildVersion = attributes.getValue("Build-Version");
    buildDate = attributes.getValue("Build-Date");
    buildRevision = attributes.getValue("Build-Revision");
    buildNumber = attributes.getValue("Build-Number");
%>

一个优点是,此信息也以易于查找的文档形式出现在清单中。缺点之一是需要打开和读取清单文件。