【问题标题】:Spring Webflux: optional RequestPart/RequestParam is still required?Spring Webflux:仍然需要可选的 RequestPart/RequestParam?
【发布时间】:2018-10-10 09:58:58
【问题描述】:

我正在尝试使用可选的请求参数/请求部分,但是当我不提供可选参数时,我的请求就会无限期挂起。

@RestController
@RequestMapping("/service")
class MyController {
    @PostMapping
    fun print(@RequestPart("name", required = false) name: String) {
        if (name != null)
            print(name)
        else
            print("grr")
    }
}

如果我在我的请求中提供参数name,它在邮递员中不再挂起,请求通过。但是当我不提供参数name 并打印“grr”时,我希望它无论如何都会通过。

当您添加另一个所谓的可选属性时,会验证此必需属性(至少在我看来)无法正常工作。

@RestController
@RequestMapping("/service")
class MyController {
    @PostMapping
    fun print(@RequestPart("name", required = false) name: String,
              @RequestPart("friend_name", required = false) friendsName: String) {
        if (name != null)
            print(name)
        else
            print("grr")
    }
}

现在当我提供参数name 但不提供friend_name 时,它表示该值不能为空。

{
    "timestamp": "2018-10-10T09:50:49.305+0000",
    "path": "/service",
    "status": 500,
    "error": "Internal Server Error",
    "message": "Parameter specified as non-null is null: method co.example.controllers.MyController.print, parameter friendsName"
}

我对@9​​87654328@ 和@RequestPart 进行了相同的尝试,结果相同。

【问题讨论】:

  • 所以使用可空运算符?实际上解决了这个问题哈哈。如果您想发布答案,我会将其标记为已接受:) -> 它使用的是@RequestPart,因为我的实际代码是multipart/form-data

标签: java spring spring-boot kotlin


【解决方案1】:

将您的可选参数标记为可为空。因此:

@RequestPart("name", required = false) name: String?
@RequestPart("friend_name", required = false) friendsName: String?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    • 2017-04-30
    • 2015-09-06
    • 1970-01-01
    • 2018-08-13
    • 2021-05-02
    相关资源
    最近更新 更多