Tomcat 7 - Retrieve the version of a webapp (versi

2019-03-30 19:58发布

I've been unable to find any easy way of figuring out the version string for a WAR file deployed with Tomcat 7 versioned naming (ie app##version.war). You can read about it here and what it enables here.

It'd be nice if there was a somewhat more supported approach other than the usual swiss army knife of reflection powered ribcage cracking:

final ServletContextEvent event ...
final ServletContext applicationContextFacade = event.getServletContext();
final Field applicationContextField = applicationContextFacade.getClass().getDeclaredField("context");
applicationContextField.setAccessible(true);
final Object applicationContext = applicationContextField.get(applicationContextFacade);
final Field standardContextField = applicationContext.getClass().getDeclaredField("context");
standardContextField.setAccessible(true);
final Object standardContext = standardContextField.get(applicationContext);
final Method webappVersion = standardContext.getClass().getMethod("getWebappVersion");
System.err.println("WAR version: " + webappVersion.invoke(standardContext));

3条回答
▲ chillily
2楼-- · 2019-03-30 20:37

I think the simplest solution is using the same version (SVN revision + padding as an example) in .war, web.xml and META-INF/MANIFEST.MF properties files, so you could retrieve the version of these files later in your APP or any standard tool that read version from a JAR/WAR

See MANIFEST.MF version-number

查看更多
何必那么认真
3楼-- · 2019-03-30 20:43

Another solution described here uses the path name on the server of the deployed WAR. You'd extract the version number from the string between the "##" and the "/"

runningVersion = StringUtils.substringBefore(
                 StringUtils.substringAfter(
                     servletConfig.getServletContext().getRealPath("/"),
                     "##"),
                 "/");
查看更多
疯言疯语
4楼-- · 2019-03-30 20:50

The easiest way would be for Tomcat to make the version available via a ServletContext attribute (org.apache.catalina.core.StandardContext.webappVersion) or similar. The patch to do that would be trivial. I'd suggest opening an enhancement request in Tomcat's Bugzilla. If you include a patch then it should get applied fairly quickly.

查看更多
登录 后发表回答