Teja Kantamneni Teja Kantamneni - 3 months ago 45
Java Question

Get the server port number from tomcat with out a request

Is there any Tomcat API or configuration available which can tell an application (probably on startup), what port its running on without a request??

*EDIT*

Imagine a scenario where there are two web applications running in the same tomcat and one of which need to invoke a web service from the other one. We don't want the request to leave the tomcat (if you use the apache server name or absolute URL, the request will go out and come back again and it can go to any instance) and come back in. For that I know the name of the machine but no way to get the port number. I know I can hard code this information but I don't want to do this as I want my

war
file to be application server agnostic.

**I know that we can find it if we have a HTTPServletRequest

*EDIT (10/18/2013)**
This works only for Tomcat 6 and will not work on Tomcat 7

Answer

For anybody who is interested in how we solved this, here is the mock code

Server server = ServerFactory.getServer();
        Service[] services = server.findServices();
        for (Service service : services) {
            for (Connector connector : service.findConnectors()) {
                ProtocolHandler protocolHandler = connector.getProtocolHandler();
                if (protocolHandler instanceof Http11Protocol
                    || protocolHandler instanceof Http11AprProtocol
                    || protocolHandler instanceof Http11NioProtocol) {
                    serverPort = connector.getPort();
                    System.out.println("HTTP Port: " + connector.getPort());
                }
            }


        }