【问题标题】:How can I set param as not required in micronaut GET request?如何在 micronaut GET 请求中将参数设置为不需要?
【发布时间】:2020-09-30 20:05:16
【问题描述】:

我需要在我的请求中将参数设置为不需要。

我试过了:

 @Get(value = "/list/{username}")
 HttpResponse<?> list(String username, @QueryValue(value = "actionCode") String actionCode) {
     ...
 }

当我发送请求时 http://localhost:8080/notification/list/00000000000 抛出以下错误:

{
    "message": "Required Parameter [actionCode] not specified",
    "path": "/actionCode",
    "_links": {
        "self": {
            "href": "/notification/list/00000000000",
            "templated": false
        }
    }
}

【问题讨论】:

    标签: micronaut micronaut-client micronaut-rest


    【解决方案1】:

    您可以通过javax.annotation.Nullable注解将Micronaut中的查询参数定义为可选:

    import io.micronaut.http.annotation.Controller;
    import io.micronaut.http.annotation.Get;
    import io.micronaut.http.annotation.QueryValue;
    import javax.annotation.Nullable;
    
    @Controller("/sample")
    public class SampleController {
        @Get("/list/{username}")
        public String list(
            String username,
            @Nullable @QueryValue String actionCode
        ) {
            return String.format("Test with username = '%s', actionCode = '%s'", username, actionCode);
        }
    }
    

    以下是示例调用及其结果。没有actionCode的电话:

    $ curl http://localhost:8080/sample/list/some-user
    Test with username = 'some-user', actionCode = 'null'
    

    拨打actionCode:

    $ curl http://localhost:8080/sample/list/some-user?actionCode=some-code
    Test with username = 'some-user', actionCode = 'some-code'
    

    如您所见,没有错误,它在 Micronaut 版本 1 和版本 2 中都以这种方式工作。

    【讨论】:

    • 我忘了在问题描述中提及,但我已经尝试过@Nullable,但它没有用。发生同样的错误。
    • 它必须有效。我通过示例 curl 调用将完整的示例控制器类添加到答案中。尝试一下。如果您仍然有错误,那么问题一定出在其他地方。
    • 我的错。问题出在 Nullable 注释导入中。当我设置 javax.annotation.Nullable 时,它​​可以工作。谢谢你。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    • 2020-03-11
    • 2019-08-31
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多