在没有请求的情况下从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屋!