如何在 Spring Boot RestController 中映射动态查询参数

jam*_*246 2 java query-parameters spring-boot spring-restcontroller

是否可以使用 Spring Boot 使用动态名称映射查询参数?我想映射如下参数:

/products?filter[name]=foo
/products?filter[length]=10
/products?filter[width]=5
Run Code Online (Sandbox Code Playgroud)

我可以做这样的事情,但这需要知道每个可能的过滤器,我希望它是动态的:

@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
    ) {
        //
    }
}
Run Code Online (Sandbox Code Playgroud)

如果可能,我正在寻找允许用户定义任意数量可能的过滤器值的东西,以及那些HashMap被 Spring Boot映射为 a的东西。

@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");
    }
}
Run Code Online (Sandbox Code Playgroud)

发布在此问题上的答案建议使用@RequestParam Map<String, String> parameters,但是这将捕获所有查询参数,而不仅仅是那些匹配的filter[*].

Sma*_* Ma 5

您可以在@RequestParam使用映射时映射多个参数而无需定义它们的名称:

@GetMapping("/api/lala")
public String searchByQueryParams(@RequestParam Map<String,String> searchParams) {
    ...
}
Run Code Online (Sandbox Code Playgroud)