6

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?

1
  • Hi, I'm also looking for same, if you got a solution, please update Commented Feb 3, 2020 at 7:25

2 Answers 2

10

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) { 
.... 
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.