Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
976 views
in Technique[技术] by (71.8m points)

list - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...