简体   繁体   中英

Spring RequestParam Map<String, String>

I have this in my controller:

@RequestMapping(value = "/myUrl", method = RequestMethod.GET)
public String myUrl(@RequestParam(value = "test") Map<String, String> test)
{
    return test.toString();
}

And I'm making this HTTP request:

GET http://localhost:8080/myUrl?test[a]=1&test[b]=2

But in the logs I'm getting this error:

org.springframework.web.bind.MissingServletRequestParameterException: Required Map parameter 'test' is not present

How can I pass Map<String, String> to Spring?

May be it's a bit late but this can be made to work by declaring an intermediate class:

public static class AttributeMap {
    private Map<String, String> attrs;

    public Map<String, String> getAttrs() {
        return attrs;
    }

    public void setAttrs(Map<String, String> attrs) {
        this.attrs = attrs;
    }
}

And using it as parameter type in method declaration (w/o @RequestParam):

@RequestMapping(value = "/myUrl", method = RequestMethod.GET)
public String myUrl(AttributeMap test)

Then with a request URL like this: http://localhost:8080/myUrl?attrs[1]=b&attrs[222]=aaa

In test.attrs map all the attributes will present as expected.

It's not immediately clear what you are trying to do since test[a] and test[b] are completely unrelated query string parameters.

You can simply remove the value attribute of @RequestParam to have your Map parameter contain two entries, like so

{test[b]=2, test[a]=1}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM