连接到127.0.0.1端口8080失败:连接被拒绝

时间:2020-02-07 11:11:12

标签: java spring rest curl spring-restcontroller

我使用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方法效果很好。

1 个答案:

答案 0 :(得分:1)

为了在不使用Spring Boot的情况下通过Spring出席HTTP请求,通常需要以下条件:

  1. 使用spring-webmvc依赖项。我了解您已经拥有。
  2. 打包您的应用程序作为一场战争。如果使用Maven进行构建,则需要在pom.xml中添加<packaging>war</packaging>句子
  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中找到另一个示例。