【问题标题】:How to access endpoints in a controller in Spring?如何在 Spring 中访问控制器中的端点?
【发布时间】:2017-10-24 03:59:42
【问题描述】:

我有一个带有端点的控制器类。我知道我们可以通过使用 URL 的“邮递员”等工具访问 Web 应用程序中的 RESTful 端点。但我不确定如何访问这些端点。这不是一个网络应用程序。

这是一个使用嵌入式 tomcat 在服务器上部署为 JAR 的 java 应用程序。

如何访问这些端点?

@Controller
public class TopicStatsController {

    @Autowired
    private QueueDepths depths;

    @RequestMapping("/topicDepth")
    @ResponseBody
    public Long topicDepth() throws Exception {
        return depths.topicDepth();
    }

    @RequestMapping("/subscribersDepth")
    @ResponseBody
    public List<Long> subscribersDepth() throws Exception {
        return depths.subscribersDepth();
    }
}

【问题讨论】:

  • 它仍然是一个 Web 应用程序,要么作为战争部署在传统的 Tomcat 服务器上,要么作为带有嵌入式 Tomcat 的 jar 执行。只需使用 Postman 发出 GET 或 curl 到即 localhost:&lt;port&gt;/topicDepth
  • 如果您在pom.xml 中使用spring-bootweb-starter,即使这是一个独立的JAR 并且没有部署在Web 服务器上,它也是一个Web 应用程序。这就是 spring-boot 的美妙之处。
  • @FedericoPeraltaSchaffner 我应该在哪里使用 Postman 发出 GET?应用程序位于远程服务器上,而不是我的计算机上。对于远程服务器上的应用程序,我如何说 localhost:/topicDepth?
  • @hars 将localhost:&lt;port&gt; 替换为远程服务器的IP:&lt;port&gt;
  • 您尚未接受任何问题的答案。如果它解决了您的问题,请考虑接受答案。查看this

标签: java spring spring-boot


【解决方案1】:

您可以使用RestTemplate 访问端点。

RestTemplate restTemplate = new RestTemplate();
String fooResourceUrl
  = "/topicDepth";
ResponseEntity<String> response
  = restTemplate.getForEntity(fooResourceUrl + "/1", Long.class);

【讨论】:

    【解决方案2】:

    您的遥控器必须有一个IP地址和一个端口号

    您可以使用它来发送GETPOST 请求。

    在本地主机上 - http://localhost:8080/myapp-oracle/api/v1/user

    远程 - http://172.16.254.1:8080/myapp-oracle/api/v1/user

    注意:您还需要根据服务器更改http协议。

    【讨论】:

      猜你喜欢
      • 2019-06-09
      • 1970-01-01
      • 2018-04-17
      • 2015-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多