【问题标题】:Spring @RequestMapping with optional parameters when using custom request object使用自定义请求对象时带有可选参数的 Spring @RequestMapping
【发布时间】:2020-05-20 16:09:16
【问题描述】:

您好,我想在我的控制器上创建一个可选参数,id,到目前为止看起来像这样

    @ApiOperation(value = "get runs by date in order to paginate")
    @ApiResponses({ @ApiResponse(code = 200, message = "Success"),
            @ApiResponse(code = 500, message = "Unexpected failure") })
    @RequestMapping(value = "/time/{date}/to/{toPage}/from/{fromPage}",
                    params = {"pageSize", "id"},
                    method = RequestMethod.GET)
    public RunCollection getPolicyByDate(GetPolicyByDateRequest request) {
        return serviceImpl.getListOfRunsByDate(request);
    }

但这意味着该参数是必需的。我希望它是可选的。我在他们使用 @RequestParam Spring @RequestMapping with optional parameters 的地方看到了这个答案,但我想将它包含在我的 GetPolicyByDateRequest 对象中。这可能吗? spring 文档没有提到关闭 required 属性。我可以使用Optional

【问题讨论】:

  • "我想将它包含在我的 GetPolicyByDateRequest 对象中" GET 请求没有任何正文。我不确定您打算如何从 GET 请求中获取 GetPolicyByDateRequest 方法参数?
  • 因为这是在幕后,我不确定它是如何工作的@narendra-choudhary。请求对象不保存所有请求数据吗?因为只要名称相同,它就可以提取所有其他 4 个参数
  • 看看this guide 使用@PathVariable
  • 我知道我可以用@RequestParam 做到这一点,但我想将它保留在我的Request 对象中。这就是问题

标签: java spring controller


【解决方案1】:

2 个选项:

  1. 如果您的GetPolicyByDateRequest 没有原始属性,它们应该由 Spring 插入到您的对象中。如果您的参数未设置(即您的 url 中没有 pageSize),则 Spring 在您的属性中注入 NULL。
public class GetPolicyByDateRequest {

    private String date;
    private int toPage;
    private int fromPage;
    private Integer pageSize;
    private Integer id;

    public GetPolicyByDateRequest() {
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public int getToPage() {
        return toPage;
    }

    public void setToPage(int toPage) {
        this.toPage = toPage;
    }

    public int getFromPage() {
        return fromPage;
    }

    public void setFromPage(int fromPage) {
        this.fromPage = fromPage;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "MyRequest{" +
                "date='" + date + '\'' +
                ", toPage=" + toPage +
                ", fromPage=" + fromPage +
                ", pageSize=" + pageSize +
                ", id=" + id +
                '}';
    }
}

奇怪的是,我认为这是 Spring 中的一些错误之王,即使在使用 Optional 时,如果未提供 requestParam 中的参数,您也会得到一个空对象。

  1. 如果你想获取所有参数,你需要在你的情况下使用@PathVariable@RequestParam。以下是获取参数的方法:
 @RequestMapping(value = "/time/{date}/to/{toPage}/from/{fromPage}", method = RequestMethod.GET)
    public RunCollection getPolicyByDate(@PathVariable String date, @PathVariable int toPage, @PathVariable int fromPage, @RequestParam(required = false) Optional<Integer> pageSize, @RequestParam(required = false) Optional<Integer> id) {
        // then use your parameters the way you to use then.
    }

请注意:

  • @PathVariable 检索 URL 中的参数,其中值在 {} 之间,如 {date} -> @PathVariable String date
  • @RequestParam 检索 URL 中 ? 之后的参数。 ?pageSize=10 -> @RequestParam int pageSize.
  • 这两个注释都作为参数,其中包括required=true|false。将参数标记为不需要时,请确保您不使用原始类型,如 int,否则,您可以将此对象设置为 null,您的代码将在运行时失败。这就是我使用Optional&lt;Integer&gt; 来允许该类型的原因。但是 Spring 很聪明,如果它在你的参数中检测到Optional,那么你就不得不在@RequestParam 中使用required=false

如果您想填充您的GetPolicyByDateRequest,那么您应该进行POST 映射,并使用注释@RequestBody GetPolicyByDateRequest request,并在您的请求中发送一个JSON 正文,以使Spring(实际上是Jackson)翻译您的JSON到 GetPolicyByDateRequest 对象中。

希望对你有帮助

【讨论】:

  • 您的第一个选项是我的设置,但如果参数不存在,spring 会抱怨。我正在寻找一种方法将其保留在请求对象中而不需要它是强制性的
  • 你的春季版本是什么?因为它对我很有效
  • 看起来像 4.2.1 我在传递一个而不是另一个参数时收到此错误There was an unexpected error (type=Bad Request, status=400). Parameter conditions "pageSize, id" not met for actual request parameters: pageSize={25}
  • 查看此链接,似乎在任何版本上都不可能baeldung.com/spring-request-param
  • 去掉params = {"pageSize", "id"},属性试试看。
猜你喜欢
  • 1970-01-01
  • 2018-08-30
  • 2012-03-02
  • 2021-03-02
  • 2014-03-10
  • 2015-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多