0

There should be a straightforward way to do this, but most answers on the net provide the port of an embedded Tomcat server using something like ${server.port} (or its equivalent). Other solutions mention listening to EmbeddedServletContainerInitializedEvent but this also is only applicable to embedded web servers.

How can I obtain the port of an application that's deployed on (let's say) JBoss where the port is decided through the server's own configuration file (and not through application.properties)?

(P.S: In Spring Boot 2, there is an event called WebServerInitializedEvent, using which we can probably get the true port, but I'm looking for solutions up to Spring Boot 1.5.8)

Daud
  • 7,429
  • 18
  • 68
  • 115
  • `System.getProperty("server.port")` – Elliott Frisch Nov 07 '19 at 09:21
  • @ElliottFrisch That just gives the port configured in *application.properties* – Daud Nov 07 '19 at 09:22
  • 1
    You'll need to use some code that's specific to your application server. Here's someone asking the same question for JBoss: https://stackoverflow.com/questions/24741004/how-to-get-bound-server-address-and-port-programmatically-in-java-ee – Andy Wilkinson Nov 07 '19 at 09:32
  • Depending on what you need it for, just call [`servletRequest.getLocalPort()`](https://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getLocalPort()). You can get the `ServletRequest` object as a parameter on your controller methods. --- The container may listen on more than one port, and may be behind a proxy server, so the real port is only known when a request is received. – Andreas Nov 07 '19 at 09:49

1 Answers1

0

I believe the port on which the application server (JBoss and others) is ready to accept http connection is something internal to the application server itself and kind of "out-of-scope" for spring boot application when it doesn't run the embedded server.

Its also possible that the application server will define multiple connectors bound to different ports (say, one for http and one for https), internal vs. "public" connections (filtering by ip segments) and what not.

Usually the developers don't care about this kind of information, if you need to generate some link, do it "relatively". Usually you don't even need to know the context path under which the WAR is deployed.

Now if you absolutely need something like this, there is no common guideline for this, every application server might provide its own ways.

You can try to access JMX (for example Tomcat that used to run inside JBoss, I might be not updated on this, haven't dealt with JBoss for a long time) exposes MBean for Connector from which you can read the port information (of many ports if many connectors are deployed).

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97