Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RequestParam as Set in single parameter

I created endpoint with param as set:

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

Everything works fine, but I need to send ids separetly e.g.

/me?param=1&param=2

Is there a way to make it as:

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

Any ideas? Thanks.

like image 288
degath Avatar asked Oct 28 '18 09:10

degath


2 Answers

you can do something like this

@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);
    }

So if you hit --> localhost:8786/me?param=hello,foo,bar,animals , you will get below response

[ "animals", "bar", "foo", "hello" ]

like image 137
Amit Kumar Lal Avatar answered Sep 29 '22 00:09

Amit Kumar Lal


Okay I tested it in a new "Spring Environment" created on start.spring.io

It works out of the box, as already one in the comments said, but only with an Array of Integers (Not with a Set). If you are gonna use one of the listed options you can remove duplicates of numbers (I guess this was your intention by using a Set) just with Set<Integer> ints = Arrays.stream(params).collect(Collectors.toSet())

When there definitely will be no "empty" number:

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

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

Output (As expected an array of integers):

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

]

And if there's probably an empty number in it, I would suggest to use Integer as an array.

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

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

Output (with null values because there are empty fields in the query):

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

]

like image 42
Markus G. Avatar answered Sep 28 '22 22:09

Markus G.