Spring @RequestMapping with optional parameters

13,039

Solution 1

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) { 
.... 
}

Solution 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.

Share:
13,039
Tomasz
Author by

Tomasz

Updated on June 30, 2022

Comments

  • Tomasz
    Tomasz almost 2 years

    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?