How to map dynamic query parameters in Spring Boot RestController

13,370

Solution 1

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

Solution 2

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]

}

Share:
13,370
james246
Author by

james246

Updated on June 27, 2022

Comments

  • james246
    james246 almost 2 years

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

  • james246
    james246 over 5 years
    Thanks for the response. I've chosen to format the filters using what I'd consider "standard" formatting, and what I'm used to coming from a Ruby on Rails background. I'd tend to favour the f[x]=y format. I'm adervse to rolling my own standard for representing filters, due to the possibilities for problems you cite such as SQL injection and making sure delimeters are working properly.
  • james246
    james246 over 5 years
    Interesting, I haven't seen this way of formatting query parameters before. Given it has it's own annotation in Spring (@MatrixVariable) then perhaps that is how Spring/Java services generally do it. I'm used to Rails which uses foo=bar, filter[x]=y, list[]=x&list[]=y - which I find more readable.