首页 文章

如何让Swagger UI显示类似的Spring Boot REST endpoints ?

提问于
浏览
1

我有一个带有两个 endpoints 的控制器类

@RestController
@RequestMapping
public class TestController {

  @RequestMapping(
          value= "/test",
          method = RequestMethod.GET)
  @ResponseBody
  public String getTest() {
    return "test without params";
  }

  @RequestMapping(
          value= "/test",
          params = {"param"},
          method = RequestMethod.GET)
  @ResponseBody
  public String getTest(@PathParam("param") int param) {
    return "test with param";
  }

}

一个有参数,一个没有,两者都有效 .

如果我使用curl或Web浏览器来命中 endpoints

http:// localhost:8081 / test

回报

没有参数的测试

http:// localhost:8081 / test?param = 1

回报

用param测试

但是招摇的ui只显示没有参数的那个 .

如果我使用参数to更改请求的请求映射中的值

@RequestMapping(
          value= "/testbyparam",
          params = {"param"},
          method = RequestMethod.GET)

Swagger UI正确显示两个 endpoints ,但我不想根据swagger将显示或不显示的 endpoints 来定义 endpoints .

有没有什么方法让我能够通过匹配值正确显示 endpoints ,但不同参数?

编辑澄清:

endpoints 工作得非常好; / test和/ test?param = 1都工作得很好,问题是swagger-ui不会显示它们 .

我希望swagger ui能够显示我已经定义的 endpoints ,但如果不能,那么我将不得不忍住swagger-ui错过了我的一些 endpoints .

编辑参考:

在这里回答的人:Proper REST formatted URL with date ranges

明确地说不要用斜杠分隔查询字符串

他们还说“在查询字符串之前不应该有斜杠 . ”

3 回答

  • 0

    尝试在路径中包含param,如下所示 .

    @GetMapping("/test/{param}")
    public String getTest(@PathVariable final int param) {
        return "test with param";
    }
    
  • 0

    问题出在您的Request Mapping中,第二个方法声明覆盖了第一个方法 . 由于资源映射值相同 .

    尝试将第二种方法更改为以下 . 由于您希望在QueryParam而不是路径变量中提供输入,因此您应该使用@RequestParam而不是@PathParam .

    请注意,您必须提供/ test /,以告诉Spring您的映射不明确 . 希望能帮助到你 .

    @RequestMapping(
              value= "/test/",
              method = RequestMethod.GET)
      @ResponseBody
      public String getTest (@RequestParam("param") int param) {
        return "test with param"+param;
      }
    
  • 0

    我不清楚你到底想要做什么,但我会给出两个解决方案:

    如果你想拥有PATH参数,例如 GET /testGET /test/123 你可以这样做:

    @GetMapping("/test")
      public String getTest() {
        return "test without params";
      }
    
      @GetMapping("test/{param}")
      public String getTest(@PathVariable("param") int param) {
        return "test with param";
      }
    

    如果需要查询参数( GET /testGET /test?param=123 ),则需要一个带有可选参数的 endpoints :

    @GetMapping("test")
      public String getTest(@RequestParam("param") Integer param) {
        if(param == null) { 
          return "test without params";
        } else {
          return "test with param";
        }
      }
    

相关问题