Search code examples
spring-bootcontrollerhttp-request-parameters

Is there a better way to construct a controller with multiple parameters the might not be required?


I'm making a simple spring boot application and i have to get a list of objects, which i filter by parameters that aren't required. So basically the user can send the parameters, but doesn't have to. Best solution that i found is the use of @RequestParam annotation but it doesn't seem to work. If i put both parameters it works perfectly but if I set just one or none i get an error. Do i have to overload methods for every case or is there a smoother way to deal with this(if possible by still using the get request)?

My controller:

@RequestMapping(
                value = "/fruits",
                params = {"apple", "orange"},
                method = GET)
public ResponseEntity<List<Fruit>> getFruits(
@RequestParam(value = "apple", required = false, defaultValue = "") 
List<Apple> apple,
@RequestParam(value ="orange", required = false, defaultValue = "") 
List<Orange> orange) {

List<Fruit> fruit = projectService.getFruits(apple, orange);
  return ResponseEntity.ok().body(fruit);
}

Error:

{
"timestamp": "2019-01-20T21:26:52.287+0000",
"status": 400,
"error": "Bad Request",
"message": "Parameter conditions \"apple, orange\" not met for actual 
request parameters: ",
"path": "/api/fruits"
}

Solution

  • Remove this line:

     params ={"apple","orange"} 
    

    and it will work. Because you don't need to call twice, it's enough with those @RequestParam annotations.