在ContextListener的内部部分,我如何才能找到Web正在运行的端口
我有一个以JSP页面为前端的Java应用程序项目。该项目实现了一个连接到后端的ServletContextListener。此ContextListener通过在其DBQuery方法中实例化access类DBQuery来访问数据库:
ServletContext ctx = contextEvent.getServletContext();
dbQuery = new DBQuery();
ctx.setAttribute("dbQuery", dbQuery);然后,JSP页面通过以下方式引用这个DBQuery对象
getServletContext().getAttribute("dbQuery");并根据需要调用DBQuery的方法。
现在的问题是:在DBQuery类中,根据web应用程序运行的主机和端口,我需要做不同的事情。
我找到了一种在DBQuery中确定主机名的方法:
import java.net.InetAddress;
String hostName = InetAddress.getLocalHost().getHostName();奇怪的是,InetAddress似乎没有获得端口号的方法。如何在DBQuery类中找到运行web应用程序的端口?
发布于 2020-11-04 04:26:42
在史蒂夫对GitHub要点的评论之后,我想出了以下经过调整的代码,它完全按照要求执行:
String port = "80";
try {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
Set<ObjectName> objs = mbs.queryNames( new ObjectName( "*:type=Connector,*" ),
Query.match( Query.attr( "protocol" ), Query.value( "HTTP/1.1" ) ) );
for ( ObjectName obj : objs ) {
String scheme = mbs.getAttribute( obj, "scheme" ).toString();
port = obj.getKeyProperty( "port" );
break;
}
} catch ( MalformedObjectNameException | UnknownHostException | MBeanException | AttributeNotFoundException | InstanceNotFoundException | ReflectionException ex ) {
ex.printStackTrace();
}因此,主要是实例化一个MBeanServer并使用它的属性。
https://stackoverflow.com/questions/64439742
复制相似问题