Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC + RequestParam as Map + get URL array parameters not working

I'm currently working on an API controller. This controller should be able to catch any - unknown - parameter and put it in a Map object. Now I'm using this code to catch all parameters and put them in a Map

public String processGetRequest(final @RequestParam Map params)

Now the url I call is as follows:

server/api.json?action=doSaveDeck&Card_IDS[]=1&Card_IDS[]=2&Card_IDS[]=3

Then I print out the parameters, for debugging purposes, with this piece of code:

if (logger.isDebugEnabled()) {
    for (Object objKey : params.keySet()) {
        logger.debug(objKey.toString() + ": " + params.get(objKey));
    }
}

The result of that is:

10:43:01,224 DEBUG ApiRequests:79 - action: doSaveDeck
10:43:01,226 DEBUG ApiRequests:79 - Card_IDS[]: 1

But the expected result should be something like:

10:43:XX DEBUG ApiRequests:79 - action: doSaveDeck
10:43:XX DEBUG ApiRequests:79 - Card_IDS[]: 1
10:43:XX DEBUG ApiRequests:79 - Card_IDS[]: 2
10:43:XX DEBUG ApiRequests:79 - Card_IDS[]: 3

Or atleast tell me that the Card_IDS is an String[] / List<String> and therefore should be casted. I also tried casting the parameter to a List<String> manually but that does not work either:

for (Object objKey : params.keySet()) {
    if(objKey.equals(NameConfiguration.PARAM_NAME_CARDIDS)){ //Never reaches this part
        List<String> ids = (List<String>)params.get(objKey); 

        for(String id : ids){
            logger.debug("Card: " + id);
        }
    } else {
        logger.debug(objKey + ": " + params.get(objKey));
    }
}

Could someone tell me how to get the array Card_IDS - It must be dynamically - from the Map params by using the NameConfiguration.PARAM_NAME_CARDIDS?

like image 872
Jaap Oudejans Avatar asked May 03 '13 09:05

Jaap Oudejans


1 Answers

When you request a Map annotated with @RequestParam Spring creates a map containing all request parameter name/value pairs. If there are two pairs with the same name, then only one can be in the map. So it's essentially a Map<String, String>

You can access all parameters through a MultiValueMap:

public String processGetRequest(@RequestParam MultiValueMap parameters) {

This map is essentially a Map<String, List<String>>. So parameters with the same name would be in the same list.

like image 184
a better oliver Avatar answered Nov 15 '22 07:11

a better oliver