在单个参数中设置RequestParam

时间:2018-10-28 09:15:57

标签: java spring parameters

我使用设置的参数创建了端点:

@GetMapping("/me")
public MeDto getInfo(@RequestParam("param") Set<Integer> params) {
    ...
}

一切正常,但我需要分别发送ID,例如

/me?param=1&param=2

有没有办法使它成为:

/me?param=1,2...N

有什么想法吗?谢谢。

2 个答案:

答案 0 :(得分:4)

您可以这样做

@RequestMapping(method=RequestMethod.GET, value="/me")
    public ResponseEntity<?> getValues(@RequestParam String... param){
        Set<String> set= new TreeSet<String>(Arrays.asList(param));
        return new ResponseEntity<Set>(set, HttpStatus.OK);
    }

因此,如果您点击-> localhost:8786 / me?param = hello,foo,bar,animals,则会得到以下响应

[     “动物”,     “酒吧”,     “ foo”,     “你好” ]

答案 1 :(得分:1)

好的,我在start.spring.io上创建的新“ Spring Environment”中对其进行了测试

它是开箱即用的,正如注释中已经提到的那样,但仅适用于整数数组(不适用于Set)。 如果您要使用列出的选项之一,则只需使用Set<Integer> ints = Arrays.stream(params).collect(Collectors.toSet())

即可删除数字重复项(我想这是您使用Set的目的)

当绝对没有“空”数字时:

@GetMapping("/intarray")
    public Object someGetMapping(int[] params){
        return params;
    }
  

http://localhost:8080/api/intarray?params=1,2,3,4,5,3

输出(如预期的那样,是一个整数数组):

[
1,
2,
3,
4,
5,
3

]

如果其中可能有一个空数字,我建议使用Integer作为数组。

@GetMapping("/intset")
public Object someOtherGetMapping(Integer[] params){
    return params;
}
  

http://localhost:8080/api/intset?params=1,2,3,4,5,,,5

输出(具有空值,因为查询中有空字段):

[
1,
2,
3,
4,
5,
null,
null,
5

]