Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @RequestMapping with optional parameters

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?

like image 376
Tomasz Avatar asked Mar 21 '18 09:03

Tomasz


2 Answers

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) { 
.... 
}
like image 195
kakabali Avatar answered Sep 18 '22 08:09

kakabali


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.

like image 45
GhassanMoussaif Avatar answered Sep 20 '22 08:09

GhassanMoussaif