Get Tomcat Port Number from Java Code line
Join the DZone community and get the full member experience.
Join For FreeThis code reads the port number defined in Server.XML of Tomcat, the code source is http://www.asjava.com/tomcat/how-to-get-tomcat-port-number-in-java/
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;
}
Apache Tomcat
Java (programming language)
Opinions expressed by DZone contributors are their own.
Comments