1

how can I limit @RequestParam array size in my endpoint ?? Is there any annotation for that ?

What I'm looking for is that I can send request with at most 5 parameters:

  • Correct request - http://localhost:8888/myEndpoint?param=foo1&param=foo2&param=foo3&param=foo4&param=foo5
  • Incorrect request(too many params) - http://localhost:8888/myEndpoint?param=foo1&param=foo2&param=foo3&param=foo4&param=foo5&param=foo6
  • Łukasz
    • 89
    • 1
    • 6

    2 Answers2

    0

    You need to handle this in your server code. Take an array of request parameter and check on size. I do not know any annotation for that.

    0

    If it is not important how the parameter (keys) should be called you can use a Map<K,V> as @RequestParam

    Limitation of a map entry is not possible through spring (found nothing about it). I also tried to add a Wrapper around it and Validate it with the annotation @Size, also not possible.

    Solution you can use: Make an iterator out of the Map which is coming from the request as parameter and afterwards adding the entries to a new map.

    @RequestMapping(value = "/test",method = RequestMethod.GET)
        public Object test(@RequestParam Map<String,String> map){
    
            Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
            int counter = 0; //To limit the parameter
            Map<String,String> resultMap = new HashMap<>(); //Our result map which we will return
            while (entries.hasNext() && counter < 5) { //iterate over map and stop at five entries
                Map.Entry<String, String> entry = entries.next(); //get next entry
                resultMap.put(entry.getKey(),entry.getValue()); //Put the entry in our resultMAp
                counter++; //count up
            }
            return resultMap;
        } 
    
    Markus G.
    • 1,620
    • 2
    • 25
    • 49