如何在运行时从Java代码获取server.xml中已配置的HTTP和HTTPS端口号 [英] How to get the configured HTTP and HTTPS port numbers in server.xml from Java code at runtime

查看:268
本文介绍了如何在运行时从Java代码获取server.xml中已配置的HTTP和HTTPS端口号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的项目中,我们已经使用Apache CXF框架实现了SOAP Web服务。客户端过去曾请求服务器执行某些命令。该请求包括主机,端口和用于连接的协议。如果客户端使用HTTPS配置的端口号并将协议指定为HTTP,则我们将拒绝连接-如预期的套接字异常。但是,我需要抛出一个正确的错误消息,例如无法使用http协议通过端口 ABC连接到主机 XYZ。为此,我需要在运行时从tomcat server.xml文件中获取配置的http和https端口号,然后将其与我的请求参数进行比较。

In our project, we have implemented SOAP webservices using Apache CXF framework. Clients used to request the server for some command execution. The request consists of host, port and the protocol used for connection. If the client uses a HTTPS configured port number and specify the protocol as HTTP, then we get a connection refused - socket exception as expected. But, I need to throw a proper error message like "Unable to connect to host "XYZ" with port "ABC" using http protocol". For this, I need to get the configured http and https port numbers from tomcat server.xml file at runtime and then compare it with my request parameters.

任何人,请帮忙我要如何检索它?

Anyone, please help me out on how to retrieve that?

推荐答案

您始终可以解析tomcat的server.xml文件并获取端口值:

You can always parse the tomcat's server.xml file and fetch the port values:

  public static Integer getTomcatPortFromConfigXml(File serverXml) {
   Integer port;
   try {
      DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
      domFactory.setNamespaceAware(true); // never forget this!
      DocumentBuilder builder = domFactory.newDocumentBuilder();
      Document doc = builder.parse(serverXml);
      XPathFactory factory = XPathFactory.newInstance();
      XPath xpath = factory.newXPath();
      XPathExpression expr = xpath.compile
        ("/Server/Service[@name='Catalina']/Connector[count(@scheme)=0]/@port[1]");
      String result = (String) expr.evaluate(doc, XPathConstants.STRING);
      port =  result != null && result.length() > 0 ? Integer.valueOf(result) : null;
   } catch (Exception e) {
     port = null;
   }
   return port;
}

以上代码应使您从server.xml获得HTTP端口。对于HTTPS端口,必须将XPathExpression修改为

Above code should get you the HTTP port from server.xml. For HTTPS port, the XPathExpression has to be modified to

XPathExpression expr = xpath.compile
            ("/Server/Service[@name='Catalina']/Connector[@scheme='https']/@port[1]");

请注意,以上代码段均基于server.xml是标准tomcat服务器的假设服务名称定义为 Catalina的文件。以下是标准的server.xml文件:

Please note that the above snippets are based on the assumption that the server.xml is the standard tomcat's server file where the service name is defined as "Catalina". Following is a standard server.xml file:

<Server>
    <Service name="Catalina">
        <Connector port="8080">
            #...
        </Connector>
    </Service>
</Server>

参考:代码链接

这篇关于如何在运行时从Java代码获取server.xml中已配置的HTTP和HTTPS端口号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆