如何使用@RequestParam(value =" foo")Map< MyEnum,String>在Spring控制器?
我想在我的Spring控制器中使用一些 Map< MyEnum,String>
作为 @RequestParam
现在我做了以下:
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());
}
}
}
获取EVERY参数。因此,如果我调用?FOO = BAR
的URL,它会输出 FOO:BAR
。所以它绝对需要每个String,而不只是在 MyEnum
中定义的字符串。
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
.
所以我想,为什么不命名参数: @RequestParam(value =foo)Map< MyEnum,String> test
。但是我只是不知道如何传递参数,我总是得到 null
。
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
它说:如果方法参数映射< String,String>
或 MultiValueMap< String,String>
..] 。因此,必须可以使用 value =foo
,并以某种方式设置值;)
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 ;)
em>如果方法参数类型为 Map
并且指定了请求参数名称,则请求参数值将转换为 Map $ c
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());
}
}
}
可以处理此...
@RequestParam(value="foo") Map<MyEnum, String>
以上工作: -
您必须传递以下格式的值
foo [MyTestA] = bar
foo [MyTestB] = bar2
For Above to work:-
You have to pass values in below format
foo[MyTestA]= bar
foo[MyTestB]= bar2
现在绑定String,例如MyTestA,MyTestB 等到你的MyEnum
你必须定义一个转换器。请查看此链接
Now to bind String such as "MyTestA","MyTestB" etc..to your MyEnum
You have to define a converter . Take a look a this link