獲取當前Tomcat實例的端口

有時須要在當前代碼中獲取當前Server實例的端口號, 經過HttpServletRequest請求能夠, 但有時也須要在沒有請求的狀況下獲取到端口號.code

用如下方法是能夠獲取到的:server

public int getHttpPort() {
    try {
        MBeanServer server;
        if (MBeanServerFactory.findMBeanServer(null).size() > 0) {
            server = MBeanServerFactory.findMBeanServer(null).get(0);
        } else {
            log.error("no MBeanServer!");
            return -1;
        }

        Set names = server.queryNames(new ObjectName("Catalina:type=Connector,*"),
                Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));

        Iterator iterator = names.iterator();
        if (iterator.hasNext()) {
            ObjectName name = (ObjectName) iterator.next();
            return Integer.parseInt(server.getAttribute(name, "port").toString());
        }
    } catch (Exception e) {
        log.error("getHttpPort", e);
    }
    return -1;
}
相關文章
相關標籤/搜索