【问题标题】:Spring - Springboot controller GET requests with default parametersSpring - 带有默认参数的 Spring Boot 控制器 GET 请求
【发布时间】:2020-11-09 18:16:07
【问题描述】:

我有一个带有两个 GET 端点的 Springboot 控制器:

@RestController
@RequestMapping("/foo")
class MyController {

    fun getFoo(
        @RequestParam("x", required = false) x: Int = 0
    ) = ...

    fun getFoo(
        @RequestParam("x", required = true) x: Int,
        @RequestParam("y", required = true) y: Int
    ) = ...

我想要的行为是调用时:

  • /foo 使用可选的 x 参数调用第一个端点。
  • /foo?x=123 使用提供的 x 参数调用第一个端点。
  • /foo?x=123&y=456' calls the second endpoint with the supplied xandy` 参数。

目前我收到一个错误:

{
    "timestamp": "2020-07-20T13:11:24.732+0000",
    "status": 400,
    "error": "Bad Request",
    "message": "Parameter conditions \"x\" OR \"x, y\" not met for actual request parameters: ",
    "path": "/foo"
}

在指定零参数时如何确定默认端点?

【问题讨论】:

    标签: spring spring-boot kotlin


    【解决方案1】:

    如果你想要不止一个映射到同一个 url(很多时候它是一个代码错误,但有时它是必要的,你可以在 @GetMapping@RequestMapping 注释的参数元素中使用过滤器参数。

    @RestController
    @RequestMapping("/foo")
    class MyController {
    
        @GetMapping(params = ["!y"])
        fun getFoo(
            @RequestParam("x", required = false) x: Int?
        ) = ...
    
        @GetMapping(params = ["x", "y"])
        fun getFoo(
            @RequestParam("x", required = true) x: Int,
            @RequestParam("y", required = true) y: Int
        ) = ...
    
    }
    

    【讨论】:

      【解决方案2】:

      @RequestMapping 或其变体(@GetMapping@PostMapping 等)中设置params

      例如。

      @GetMapping(params=arrayOf("!x", "!y"))
      fun getFoo()
      
      @GetMapping(params=arrayOf("x", "!y"))
      fun getFoo(
              @RequestParam("x", required = true) x: Int = 0
      
      @GetMapping(params=arrayOf("x", "y"))
      fun getFoo(
              @RequestParam("x", required = true) x: Int,
              @RequestParam("y", required = true) y: Int
          
      

      可以在同一个 URI 上应用和识别不同的参数。

      【讨论】:

        【解决方案3】:

        您可以在@RequestParam 中将defaultValue 指定为String

        fun getFoo(
            @RequestParam(name = "x", required = false, defaultValue = "0") x: Int,
            @RequestParam(name = "y", required = false, defaultValue = "1") y: Int
        ) =
        

        Spring 将使用与您指定x 作为参数相同的方法(相同的强制、错误等)将String 转换为您真正想要的任何类型(在您的情况下为Int)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-12-04
          • 2022-12-22
          • 2019-10-17
          • 2019-04-17
          • 1970-01-01
          • 2020-07-12
          • 2018-11-24
          相关资源
          最近更新 更多