嵌入式 tomcat java 应用程序正在运行,但无法访问服务器

Mat*_*att 6 java tomcat embedded-tomcat-8

我正在尝试设置一个基本的嵌入式 Tomcat 服务器,但无法运行 Tomcat 服务器。

public class Main {

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

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

        tomcat.start();
        tomcat.getServer().await();
    }
}
Run Code Online (Sandbox Code Playgroud)

在 Eclipse 中运行这个 java 应用程序提供输出:

2019 年 6 月 19 日下午 12:00:00 org.apache.catalina.core.StandardService startInternal

信息:启动服务 [Tomcat]

然后等到我按预期停止,但是当我curl localhost:8888在终端中运行时,我得到curl: (7) Failed connect to localhost:8888; 连接被拒绝

我完全按照教程进行操作,但似乎无法让服务器实际运行。此外,netstat -nlt不显示端口8888正在打开。

build.gradle有一个依赖:

implementation 'org.apache.tomcat.embed:tomcat-embed-core:9.0.21'
Run Code Online (Sandbox Code Playgroud)

有什么我在这里想念的吗?

Tra*_*ger 12

Tomcat 9 不再像以前的版本那样默认添加 Connector。您可以执行以下操作来添加一个:

final Connector connector = new Connector();
connector.setPort(port);
tomcat.getService().addConnector(connector);
Run Code Online (Sandbox Code Playgroud)

正如另一个答案中提到的,您还可以调用tomcat.getConnector();which 是一个侧面影响的吸气剂。

  • 作为背景/参考,此更改是在 Tomcat 9.0.0 Milestone 14 中引入的:[停止在嵌入模式下启动时创建默认连接器](https://bz.apache.org/bugzilla/show_bug.cgi?id=60368) 。当您使用 [`new Connector()`](https://tomcat.apache.org/tomcat-10.0-doc/api/org/apache/catalina/connector/Connector.html#%3Cinit%3E()) 时,默认情况下,您会获得“HTTP/1.1 NIO”连接器。 (2认同)

Ale*_*rov 6

我刚刚找到了我使用 tomcat 9 的解决方案,看起来我们需要getConnector()tomcat对象上调用方法。

    Tomcat tomcat = new Tomcat();
    tomcat.setPort(8080);
    tomcat.getConnector();
Run Code Online (Sandbox Code Playgroud)