小编Tom*_*asz的帖子

带有可选参数的Spring @RequestMapping

我的控制器在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));
}
Run Code Online (Sandbox Code Playgroud)

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

/getBooks?from=123&to=123
Run Code Online (Sandbox Code Playgroud)

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

/getBooks?from=123
Run Code Online (Sandbox Code Playgroud)

要么

/getBooks?to=123
Run Code Online (Sandbox Code Playgroud)

转到“ getAlerts”方法

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

java api rest spring spring-boot

4
推荐指数
2
解决办法
5883
查看次数

标签 统计

api ×1

java ×1

rest ×1

spring ×1

spring-boot ×1