有时需要在当前代码中获取当前Server实例的端口号, 通过HttpServletRequest请求可以, 但有时也需要在没有请求的情况下获取到端口号.
用以下方法是可以获取到的:
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;
}