无需请求即可从tomcat获取服务器端口号 [英] Get the server port number from tomcat without a request
问题描述
是否有任何可用的 Tomcat API 或配置可以告诉应用程序(可能在启动时),它在没有请求的情况下运行在哪个端口上?
Is there any Tomcat API or configuration available which can tell an application (probably on startup), what port its running on without a request?
想象一个场景,有两个 Web 应用程序运行在同一个 Tomcat 中,其中一个需要从另一个调用 Web 服务.我们不希望请求离开 Tomcat(如果您使用 Apache 服务器名称或绝对 URL,请求将出去并再次返回,它可以转到任何实例)并返回.为此我知道机器的名称,但无法获取端口号.我知道我可以对这些信息进行硬编码,但我不想这样做,因为我希望我的 war
文件与应用程序服务器无关.
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.
我知道如果我们有 HTTPServletRequest 就可以找到它
I know that we can find it if we have a HTTPServletRequest
这仅适用于 Tomcat 6,不适用于 Tomcat 7
This works only for Tomcat 6 and will not work on Tomcat 7
推荐答案
对于任何对我们如何解决这个问题感兴趣的人,这里是模拟代码
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());
}
}
}
这篇关于无需请求即可从tomcat获取服务器端口号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!