How to use @RequestParam(value=“foo”) Map

2019-07-23 11:22发布

问题:

I want to use some Map<MyEnum, String> as @RequestParam in my Spring Controller. For now I did the following:

public enum MyEnum {
    TESTA("TESTA"),
    TESTB("TESTB");

    String tag;

    // constructor MyEnum(String tag) and toString() method omitted
}

@RequestMapping(value = "", method = RequestMethod.POST)
public void x(@RequestParam Map<MyEnum, String> test) {
    System.out.println(test);
    if(test != null) {
        System.out.println(test.size());
        for(Entry<MyEnum, String> e : test.entrySet()) {
            System.out.println(e.getKey() + " : " + e.getValue());
        }
    }
}

This acts strange: I just get EVERY Parameter. So if I call the URL with ?FOO=BAR it outputs FOO : BAR. So it definitely takes every String and not just the Strings defined in MyEnum.

So I thought about, why not name the param: @RequestParam(value="foo") Map<MyEnum, String> test. But then I just don't know how to pass the parameters, I always get null.

Or is there any other solution for this?


So if you have a look here: http://static.springsource.org/spring/docs/3.2.x/javadoc-api/org/springframework/web/bind/annotation/RequestParam.html

It says: If the method parameter is Map<String, String> or MultiValueMap<String, String> and a parameter name is not specified [...]. So it must be possible to use value="foo" and somehow set the values ;)

And: If the method parameter type is Map and a request parameter name is specified, then the request parameter value is converted to a Map assuming an appropriate conversion strategy is available. So where to specify a conversion strategy?


Now I've built a custom solution which works:

@RequestMapping(value = "", method = RequestMethod.POST)
public void x(@RequestParam Map<String, String> all) {
    Map<MyEnum, String> test = new HashMap<MyEnum, String>();
    for(Entry<String, String> e : all.entrySet()) {
        for(MyEnum m : MyEnum.values()) {
            if(m.toString().equals(e.getKey())) {
                test.put(m, e.getValue());
            }
        }
    }

    System.out.println(test);
    if(test != null) {
        System.out.println(test.size());
        for(Entry<MyEnum, String> e : test.entrySet()) {
            System.out.println(e.getKey() + " : " + e.getValue());
        }
    }
}

Would be surely nicer if Spring could handle this...

回答1:

@RequestParam(value="foo") Map<MyEnum, String> 

For Above to work:- You have to pass values in below format
foo[MyTestA]= bar
foo[MyTestB]= bar2

Now to bind String such as "MyTestA","MyTestB" etc..to your MyEnum
You have to define a converter . Take a look a this link