【问题标题】:Spring @RequestMapping with optional parameters带有可选参数的 Spring @RequestMapping
【发布时间】:2018-08-30 09:14:33
【问题描述】:

我的控制器在请求映射中的可选参数有问题,请查看下面的控制器:

@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Books>> getBooks() {
    return ResponseEntity.ok().body(booksService.getBooks());
}

@GetMapping(
    produces = MediaType.APPLICATION_JSON_VALUE,
    params = {"from", "to"}
)
public ResponseEntity<List<Books>>getBooksByFromToDate(
    @RequestParam(value = "from", required = false) String fromDate,
    @RequestParam(value = "to", required = false) String toDate) 
{
    return ResponseEntity.ok().body(bookService.getBooksByFromToDate(fromDate, toDate));
}

现在,当我发送如下请求时:

/getBooks?from=123&to=123

没关系,请求转到“getBooksByFromToDate”方法 但是当我使用发送类似的东西时:

/getBooks?from=123

/getBooks?to=123

它转到“getAlerts”方法

是否可以在 @RequestMapping 中设置可选参数 = {"from", "to"} ?有什么提示吗?

【问题讨论】:

  • 你好,我也在找相同的,如果你有解决方案,请更新

标签: java spring rest api spring-boot


【解决方案1】:

使用默认值。示例:-

@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Books>> getBooksByFromToDate(@RequestParam(value = "from", required = false, defaultValue="01/03/2018") String fromDate, @RequestParam(value = "to", required = false, defaultValue="21/03/2018") String toDate) { 
.... 
}

【讨论】:

    【解决方案2】:

    只需按照the Spring's docs 中的说明使用defaultValue

    默认值

    当请求参数为 未提供或值为空。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-20
      • 2018-08-16
      • 1970-01-01
      • 2016-10-20
      • 2019-04-22
      • 1970-01-01
      • 2012-11-09
      • 1970-01-01
      相关资源
      最近更新 更多