0

In the internals of an ContextListener how can I find out the port the Web App is running on

I have a Java Web app project with JSP pages as frontend. The project implements a ServletContextListener to connect to the backend. This ContextListener accesses the database by instantiating an access class DBQuery in its contextInitialized method:

ServletContext ctx = contextEvent.getServletContext();
dbQuery = new DBQuery();
ctx.setAttribute("dbQuery", dbQuery);

The JSP pages then refer to this DBQuery object via

getServletContext().getAttribute("dbQuery");

and call the methods of DBQuery as they desire.

Now the problem: In the DBQuery class I need to do different things depending on which host and on which port the web app runs.

I found a way to determine the host name in DBQuery:

import java.net.InetAddress;
String hostName = InetAddress.getLocalHost().getHostName();

Strangely InetAddress does not seem to have a method to get the port number. How can I find out in the DBQuery class on which the port the web app runs on?

halloleo
  • 9,216
  • 13
  • 64
  • 122
  • Does this help?: https://gist.github.com/devcsrj/8c44193c510d4fb1cff3 – CryptoFool Oct 20 '20 at 06:51
  • @Steve Cool! Just tried it out and it seems to work not only in the context of `contextInitialized ` but even in my own `DBQuery` object. Thanks! – halloleo Oct 20 '20 at 07:03
  • @Steve Do you want to write this up as an answer? – halloleo Oct 21 '20 at 06:40
  • I didn't really add anything. It's just that post, and that code was inspired by the SO question: http://stackoverflow.com/questions/3867197/get-the-server-port-number-from-tomcat-with-out-a-request. So maybe we should just close this as a duplicate. – CryptoFool Oct 21 '20 at 15:20
  • @Steve I disagree. The Solution might be similar, though the Question is quite different. – halloleo Oct 22 '20 at 13:42

1 Answers1

0

Following Steve's comment to look at a GitHub gist, I came up with the following adapted code which does exactly what was asked for:

String port = "80";
try {
     MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
     Set<ObjectName> objs = mbs.queryNames( new ObjectName( "*:type=Connector,*" ),
             Query.match( Query.attr( "protocol" ), Query.value( "HTTP/1.1" ) ) );
     for ( ObjectName obj : objs ) {
         String scheme = mbs.getAttribute( obj, "scheme" ).toString();
         port = obj.getKeyProperty( "port" );
         break;
     }
} catch ( MalformedObjectNameException | UnknownHostException | MBeanException | AttributeNotFoundException | InstanceNotFoundException | ReflectionException ex ) {
     ex.printStackTrace();
}

So the main thing is to instantiate a MBeanServer and utilise its attributes.

halloleo
  • 9,216
  • 13
  • 64
  • 122