I have problem in my controller with optional params in requestmapping, look on my controller below:
@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));
}
Now, when I send request like:
/getBooks?from=123&to=123
it's ok, request goes to "getBooksByFromToDate" method but when I use send something like:
/getBooks?from=123
or
/getBooks?to=123
it goes to "getAlerts" method
Is it possible to make optional params = {"from", "to"} in @RequestMapping ? Any hints?
Use the default values. Example:-
@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) {
....
}
Just use defaultValue
as explained in the Spring's docs:
defaultValue
The default value to use as a fallback when the request parameter is not provided or has an empty value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With