Over a million developers have joined DZone.

Get Tomcat Port Number from Java Code line

DZone's Guide to

Get Tomcat Port Number from Java Code line

Free Resource

This 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;

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}