如何配置rest控制器以接受动态的路径变量



我有一个api调用,它执行如下get:http://localhost/foo/barCodes?0=XXX&1=ZZZ?2=YYY它可能或多或少取决于用户的操作。。对于后端Restcontroller,最初我尝试了

@GetMapping("/foo/barCodes")
public ResponseEntity<List<Food>> getSomeFood(
@RequestParam String[] codes) { 

但我收到错误"Bad Request",消息:";方法参数类型String[]所需的请求参数"codes"不存在;。我也研究了pathvariable,但它们似乎是静态的。

我确实考虑过解析出可能具有用":"比如XXX:ZZZ:YYY或XXX:YYY,那么这将是一个值,我可以拆分它。有不同的方法吗?

1。映射多值参数

值列表可以通过如下URL传递:

http://localhost:12345/foo/barCodes?codes=firstValue,secondValue,thirdValue

http://localhost:12345/foo/barCodes?codes=firstValue&codes=secondValue&codes=thirdValue

在弹簧支架控制器中,它们可以这样接收:

@GetMapping("/foo/barCodes")
public void getSomeFood(@RequestParam String[] codes) {
// Handle values here
}

@GetMapping("/foo/barCodes")
public void getSomeFood(@RequestParam List<String> codes) {
// Handle values here
}

2.映射所有参数

我们也可以有多个参数,而不需要定义它们的名称或计数,只需使用Map。但在这种情况下,您需要将GET更改为POST方法。

@PostMapping("/foo/barCodes")
public String getSomeFood(@RequestParam Map<String,String> allParams) {
// Handle values here    
}

请求json示例:

{
"Par1":"Val1",
"Par2":"Val2"
}

curl -X POST -F 'Par1' -F 'Val1' http://localhost:12345/foo/barCodes