5

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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}

6 Comments

The documentation says that the @RequestParam should have a parameter name specified, or the map will be populated with all the request parameters: docs.spring.io/spring/docs/3.2.0.M1/api/org/springframework/web/… and that is indeed what happens. My goal is to have a map with the keys a and b, and values 1 and 2 respectively.
@stackular As far as I know, that is not possible by default. You'll need to write and register your own HandlerMethodArgumentResolver to do that.
@stackular Are the keys random? If they aren't, just use a command object.
Yes, the keys are arbitrary ("random").
@stackular AFAIK you will need then need to write your own logic to convert them to a Map (or ideally some wrapper object).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.