12

I am trying to set up a basic embedded Tomcat server and am unable to get the Tomcat server to run.

public class Main {

    public static void main(String[] args) throws LifecycleException {

        Tomcat tomcat = new Tomcat();
        tomcat.setPort(8888);

        tomcat.start();
        tomcat.getServer().await();
    }
}

Running this java app in Eclipse provides the output:

June 19, 2019 12:00:00 PM org.apache.catalina.core.StandardService startInternal

INFO: Starting service [Tomcat]

And then waits until I hit stop, as expected, but when I run curl localhost:8888 in the terminal, i get curl: (7) Failed connect to localhost:8888; Connection refused.

I've followed this tutorial exactly, but I cannot seem to get the server to actually run. Also, netstat -nlt does not show the port 8888 being open.

My build.gradle has a single dependency:

implementation 'org.apache.tomcat.embed:tomcat-embed-core:9.0.21'

Is there something I'm missing here?

Community
  • 1
  • 1
Matt
  • 902
  • 7
  • 20

2 Answers2

16

I just found solution I use tomcat 9, and it looks like we need to call method getConnector() on tomcat object.

    Tomcat tomcat = new Tomcat();
    tomcat.setPort(8080);
    tomcat.getConnector();
Alexander Kondaurov
  • 3,677
  • 5
  • 42
  • 64
9

Tomcat 9 no longer adds a Connector by default like previous versions. You can do the following to add one:

final Connector connector = new Connector();
connector.setPort(port);
tomcat.getService().addConnector(connector);

As mentioned in another answer, you can also call tomcat.getConnector(); which is a side-affecting getter.

Travis Schneeberger
  • 2,010
  • 20
  • 23
  • 1
    For background/reference, this change was introduced in Tomcat 9.0.0 Milestone 14: [Stop creating a default connector on start in embedded mode](https://bz.apache.org/bugzilla/show_bug.cgi?id=60368). When you use [`new Connector()`](https://tomcat.apache.org/tomcat-10.0-doc/api/org/apache/catalina/connector/Connector.html#%3Cinit%3E()), you get a `HTTP/1.1 NIO` connector by default. – andrewJames Aug 13 '22 at 20:12