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[*]
.
答案 0 :(得分:0)
矩阵变量对您有用吗?如果我对您的理解正确,可以这样:
// GET /products/filters;name=foo;length=100
@GetMapping(“ /产品/过滤器”) 公共无效产品( @MatrixVariable MultiValueMap matrixVars){
// matrixVars: ["name" : "foo", "length" : 100]
}
答案 1 :(得分:0)
这似乎是一个可解决的问题。据我所知,解决方案并不理想,但是有很多方法。
先前的尝试似乎是寻找一种完美的解决方案,其中在运输过程中已知过滤器的全部成分。
用户定义的全部动态条件可以使用您定义的某些基本方案进行传输,作为来自客户端的一个key = value参数,然后在收到后分解为它的元素。
您还可以发送两个参数:“字段”和“值”,其中每个字段的列表分别在其中编码,并带有一些谨慎的定界符(可以是用户无法物理键入的编码特殊字符,也许)。
与客户端提交标准(例如过滤条件)的所有其他方法一样,您仍然需要完全保护免受任何恶意使用参数的影响,就像客户端尝试将SQL标准嵌入其中一样(SQL注入) 。
但是,只要客户端代码遵循约定的语法,您就可以一次性获得来自它们的任意数量的动态参数。
客户:
/products?filter=field1--value1||field2--value2||field3--value3...
这是一个简化的示例,显示了很容易“破坏”的定界符,但是这个想法是一些简单的,甚至是完全可读(这样做没有害处)的方案,只是为了将您的字段名和值打包在一起易于运输。
服务器:
@RequestMapping(value = "/products", method = RequestMethod.GET)
public String doTheStuff(@RequestParam(value = "filter") String encodedFilter) {
.. decompose the filter here, filter everything they've sent for disallowed characters etc.
答案 2 :(得分:0)
您可以使用映射来映射多个参数而无需在logger = ulogging.uloggingConfig(fmt="format, datefmt="dateformat, teleBot=telegramBot, teleChatID=telegramChatID, teleLevel=logging.DEBUG)
logger.debug("A log message")
中定义它们的名称:
@RequestParam