Java 如何在jsp页面中获取maven项目版本号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1524824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I in a jsp page get maven project version number?
提问by Kent
I am working on a java web application, managed by maven2. From time to time, we did some changes, and want to do new releases, of course with new version number. In the homepage (jsp), there is text like
我正在开发一个由 maven2 管理的 java web 应用程序。不时,我们做了一些更改,并想做新的发布,当然还有新的版本号。在主页(jsp)中,有这样的文字
<b>version:</b> 2.3.3...
Is it possible, every time I do a new release, I only change the <version/>
in pom.xml, and version number in jsp can be automatically filled by this maven ${project.version}?
有没有可能,每次做新的release,我只<version/>
在pom.xml里改一下,jsp里的版本号就可以用这个maven ${project.version}自动填充?
I tried maven profile, however it doesn't seem to work.
我试过 Maven 配置文件,但它似乎不起作用。
any ideas?
有任何想法吗?
Thank you.
谢谢你。
采纳答案by Pascal Thivent
It's maybe stupid but I'd use a .properties
file like in this exampleinstead of filtering directly the JSP.
这可能很愚蠢,但我会使用本示例中的.properties
文件,而不是直接过滤 JSP。
回答by Rich Seller
You can use project filteringto process the JSP as it is copied to the target location. If the JSP is specified with ${project.version}
, and the containing folder is specified as a filter location the value should be substituted into the JSP as it is packaged.
您可以使用项目过滤来处理 JSP,因为它被复制到目标位置。如果使用 指定 JSP ${project.version}
,并且将包含文件夹指定为过滤器位置,则在打包 JSP 时应将其替换到 JSP 中。
For example, adding this to your POM enables filtering for src/main/resources:
例如,将它添加到您的 POM 中可以启用对 src/main/resources 的过滤:
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
Update: for war packaging, you may need to configure the war plugin to do its filtering. See the Filtering
section of the war-plugin's documentationfor more details and examples.
更新:对于 war 打包,您可能需要配置 war 插件来进行过滤。有关更多详细信息和示例,请参阅Filtering
war-plugin 的文档部分。
Essentially the process is the same, but it is defined below the war plugin, so you'd have something like this:
基本上这个过程是一样的,但它是在 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>
回答by ZZ Coder
I use this plugin,
我用这个插件
http://code.google.com/p/maven-substitute-plugin/
http://code.google.com/p/maven-substitute-plugin/
You can do something like this in Java,
你可以在 Java 中做这样的事情,
public final static String projectVersion = "@PROJECT_VERSION@";
and it's trivial to pass this value to JSP.
将这个值传递给 JSP 很简单。
回答by Jean-Rémy Revy
It make a while this post have been created, but I hope it would help. It will get properties generated from Maven :
这篇文章已经创建了一段时间,但我希望它会有所帮助。它将获取从 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>
Unfortunately, there is some drawbacks :
不幸的是,有一些缺点:
- you had to explicitely write groupId and artifactId in your code
- if you deploy your web-app directly from target/ to your server, it won't find the file because this one is in maven-archiver directory, not in META-INF, before packaging.
- 您必须在代码中明确地编写 groupId 和 artifactId
- 如果你直接从 target/ 部署你的 web-app 到你的服务器,它不会找到这个文件,因为这个文件在打包之前位于 maven-archiver 目录中,而不是在 META-INF 中。
Regards.
问候。
回答by ddcruver
In http://mojo.codehaus.org/jspc/jspc-maven-plugin/usage.html
在http://mojo.codehaus.org/jspc/jspc-maven-plugin/usage.html
It states this:
Non-WAR Projects
它说明了这一点:
非战争项目
You can also use this plugin with non-war projects, for instance to validate JSPs. They will be compiled, but not included in your final artifact, and no web.xml file will be generated or modified.
您还可以将此插件用于非战争项目,例如验证 JSP。它们将被编译,但不会包含在您的最终工件中,并且不会生成或修改 web.xml 文件。
If you want to just validate and compile your JSPs without actually including the generated code in your war project, you can also use set the includeInProject parameter to false.
如果您只想验证和编译您的 JSP,而不在您的 war 项目中实际包含生成的代码,您还可以使用将 includeInProject 参数设置为 false。
回答by whitestryder
I wanted to do this very same thing but I was not satisfied with any of the existing solutions, including using the Maven filtering approach, which is ok, but I am trying to move away from modifying existing code files during the build process so I ruled that approach out, although it is a reasonable approach.
我想做同样的事情,但我对任何现有的解决方案都不满意,包括使用 Maven 过滤方法,这是可以的,但我试图在构建过程中远离修改现有代码文件,所以我裁定那个方法出来了,虽然它是一个合理的方法。
The way I get my Maven project version into my JSP file is based on a similar approach to the one from hereexcept that I don't create a Version.java file, instead I just have Maven write the version out to a properties file, such as "version.properties" like this:
我将 Maven 项目版本放入 JSP 文件的方式基于与此处的方法类似的方法,不同之处在于我不创建 Version.java 文件,而是让 Maven 将版本写入属性文件,例如像这样的“version.properties”:
version.properties:
version.properties:
app.version = 0.1
and have Maven put it on the classpath, for instance, in src/main/resources like this:
并让 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>
Also, if you are using Spring Framework 3.x+ then you can add the following configuration to load properties in version.properties if it exists, otherwise just show "v0.0" or whatever:
此外,如果您使用的是 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;
}
}
And finally, in your /WEB-INF/views/home.jsp you can have something like:
最后,在您的 /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>
And this would of course render as:
这当然会呈现为:
The service is up and running! (v0.1)
该服务已启动并运行!(v0.1)
NOTE: If you don't use the JavaConfig classes to configure Spring Framework then you can do the same thing with Spring XML configuration.
注意:如果您不使用 JavaConfig 类来配置 Spring Framework,那么您可以使用 Spring XML 配置来做同样的事情。
回答by Daniel P.H.
You can use this in your JSP file (template.jsp in my example)
您可以在 JSP 文件中使用它(在我的示例中为 template.jsp)
<head>
<meta name="Historia Social Unica version:${version}" />
Then in your pom.xml of your project you have to activate filtering:
然后在项目的 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>
And you obtain your JSP with the variable version replaced.
并且您获得替换了变量版本的 JSP。
回答by Picrochole
Parent pom.xml:
父 pom.xml:
<properties>
<!-- in my case injected by jenkins build job -->
<build.version>dev</build.version>
<build.branch>local</build.branch>
<build.revision />
</properties>
Resource filtering (placeholders are replaced by pom-property values here)
资源过滤(占位符在这里替换为 pom-property 值)
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>conf/version.properties</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
Bean and property placeholder config in webContext.xml:
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>
Your bean looks like this then
你的豆子看起来像这样
@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;
}
}
And here comes your JSP snippet:
这是您的 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);
}
%>
回答by cosbor11
Use the maven-replacer-plugin
使用 maven-replacer-plugin
Include the plugin in your pom.xml like this:
将插件包含在你的 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>
Now anywhere in the specified file that has the token$BUILD_NUMBER$
the token will get replaced.
现在,指定文件中具有令牌$BUILD_NUMBER$
的任何位置都将替换该令牌。
回答by sschrass
I would hand the .jsp the value of
我会把 .jsp 的值交给
String version = getClass().getPackage().getImplementationVersion();
that would look like 1.0.0-SNAPSHOT
for instance.
例如,这看起来像1.0.0-SNAPSHOT
。
If you are just getting nulls, you may need to add the classpath to the Manifest of the war
with
如果您只是获取空值,则可能需要将类路径添加到war
with
<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>
for the classloader to pick it up.
以便类加载器来获取它。