java读取server.xml,如何在运行时从Java代码获取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?

解决方案

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;

}

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]");

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:

#...

Reference: Code link

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值