Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map dynamic query parameters in Spring Boot RestController

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[*].

like image 314
james246 Avatar asked Feb 25 '26 01:02

james246


2 Answers

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) {
    ...
}
like image 86
Sma Ma Avatar answered Feb 27 '26 13:02

Sma Ma


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]

}

like image 42
Juey Avatar answered Feb 27 '26 14:02

Juey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!