javaportinetaddressservletcontextlistener

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


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?


Solution

  • 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.