我的控制器中有问题,请求映射中有可选参数,请查看下面的控制器:
@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
没关系,请求转到&#34; getBooksByFromToDate&#34;方法 但是当我使用发送类似的东西时:
/getBooks?from=123
或
/getBooks?to=123
进入&#34; getAlerts&#34;方法
是否有可能在@RequestMapping中制作可选参数= {&#34;来自&#34;,&#34;到&#34;}?任何提示?
答案 0 :(得分:3)
使用默认值。例如: -
@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) {
....
}
答案 1 :(得分:2)