Spring @RequestMapping 可选参数

6

我在我的控制器中遇到了requestmapping中的可选参数问题,请查看如下控制器代码:

@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"}?有什么提示吗?


嗨,我也在寻找同样的解决方案,如果你有解决办法,请更新一下。 - VRadhe
2个回答

10

使用默认值。例如:

@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
只需按照Spring的文档中所解释的方式使用defaultValue

defaultValue

当请求参数未提供或值为空时,作为回退使用的默认值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接