【问题标题】:connect to 127.0.0.1 port 8080 failed: Connection refused [duplicate]连接到 127.0.0.1 端口 8080 失败:连接被拒绝 [重复]
【发布时间】:2020-02-07 11:11:12
【问题描述】:

我使用 Spring(不是 Boot)创建了一个简单的 RestController

@RestController
@RequestMapping(UserRestController.REST_URL)
public class UserRestController extends AbstractUserController {

    static final String REST_URL = "/users";

    @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public User get(int id) {
      return super.get(id);
  }
}

但是当我调用这个方法并使用 curl 我收到:

$ curl -v http://localhost:8080/users
Trying 127.0.0.1...
TCP_NODELAY set
connect to 127.0.0.1 port 8080 failed: Connection refused
Failed to connect to localhost port 8080: Connection refused

另外:我推送 MocMvc-test 并失败,结果如下:

java.lang.AssertionError: Status expected:<200> but was:<404>
  Expected :200
  Actual   :404

我运行我的应用程序:

public static void main(String[] args) {

try (ConfigurableApplicationContext appCtx = new 
ClassPathXmlApplicationContext("spring/spring-app.xml")) {
 System.out.println("Bean definition names: " + 
  Arrays.toString(appCtx.getBeanDefinitionNames()));
UserRestController userRestController = 
  appCtx.getBean(UserRestController.class);
        System.out.println(userRestController.get(2));
    }
}

在控制台中我看到了System.out.println(userRestController.get(2)); 的输出 所以我的 CRUD 方法效果很好。

【问题讨论】:

  • 部署了哪台服务器?
  • 这能回答你的问题吗? Curl : connection refused
  • 你的 Spring 项目开始了吗?它应该已经打印了它正在侦听的端口。向我们展示那个(仍在运行的)程序的输出。
  • 服务器...我错过了这个细节...
  • 服务器在运行吗?我 99% 确定服务器没有运行。

标签: java spring rest curl spring-restcontroller


【解决方案1】:

为了在不使用 Spring Boot 的情况下使用 Spring 处理 HTTP 请求,您通常需要以下内容:

  1. 使用 spring-webmvc 依赖。我知道你已经知道了。
  2. 将您的应用程序打包为战争。如果你用maven构建,你需要在你的pom.xml中添加&lt;packaging&gt;war&lt;/packaging&gt;这句话
  3. 在您的 web.xml 中声明 org.springframework.web.servlet.DispatcherServlet。您也可以使用org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer 进行注册。
  4. 如果使用 java-config,请在应用程序上下文文件或类中定义映射和配置。
  5. 将您的 war 文件部署在 Tomcat 或 Jetty 等 Servlet 容器中。

我以 Spring 5 here 为例。

您可以在 Spring 4 here 中找到另一个示例。

【讨论】:

  • 我在 web.xml 中忘记了 Dispatcher-servlet!
猜你喜欢
  • 2021-01-27
  • 2014-03-04
  • 2017-05-23
  • 1970-01-01
  • 2016-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多