Reputation: 79
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?
Upvotes: 6
Views: 14925
Reputation: 4033
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) {
....
}
Upvotes: 10
Reputation: 21
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.
Upvotes: 2