Is it possible to map query parameters with dynamic names using Spring Boot? I would like to map parameters such as these:
/products?filter[name]=foo
/products?filter[length]=10
/products?filter[width]=5
I could do something like this, but it would involve having to know every possible filter, and I would like it to be dynamic:
@RestController
public class ProductsController {
@GetMapping("/products")
public String products(
@RequestParam(name = "filter[name]") String name,
@RequestParam(name = "filter[length]") String length,
@RequestParam(name = "filter[width]") String width
) {
//
}
}
If possible, I'm looking for something that will allow the user to define any number of possible filter values, and for those to be mapped as a HashMap by Spring Boot.
@RestController
public class ProductsController {
@GetMapping("/products")
public String products(
@RequestParam(name = "filter[*]") HashMap<String, String> filters
) {
filters.get("name");
filters.get("length");
filters.get("width");
}
}
An answer posted on this question suggests using @RequestParam Map<String, String> parameters, however this will capture all query parameters, not only those matching filter[*].
You can map multiple parameters without defining their names in @RequestParam using a map:
@GetMapping("/api/lala")
public String searchByQueryParams(@RequestParam Map<String,String> searchParams) {
...
}
Does matrix variables work for you? If I understand you correctly, can be like this:
// GET /products/filters;name=foo;length=100
@GetMapping("/products/filters") public void products( @MatrixVariable MultiValueMap matrixVars) {
// matrixVars: ["name" : "foo", "length" : 100]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With