小编典典

如何使用@RequestParam(value =“ foo”)映射 在Spring Controller中?

spring-mvc

我想使用一些Map<MyEnum, String>@RequestParam我在春天控制器。现在,我做了以下工作:

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());
        }
    }
}

这很奇怪:我只是得到每个参数。因此,如果我用?FOO=BAR输出调用URL FOO : BAR。因此,它肯定会占用每个String,而不仅是中定义的String MyEnum

所以我想到了,为什么不给param命名呢@RequestParam(value="foo") Map<MyEnum, String> test?但是然后我只是不知道如何传递参数,我总是得到null

还是对此有其他解决方案?


因此,如果您在这里查看:http :
//static.springsource.org/spring/docs/3.2.x/javadoc-
api/org/springframework/web/bind/annotation/RequestParam.html

它说: 如果方法参数为Map<String, String>MultiValueMap<String, String>且未指定参数名[…]。因此,必须可以使用value="foo"并以某种方式设置这些值;)

并且: _如果方法参数类型为,Map并且指定了请求参数名称,则将请求参数值转换为Map假定有适当转换策略可用的值。_那么在哪里指定转换策略呢?


现在,我构建了一个自定义解决方案,该解决方案可以工作:

@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());
        }
    }
}

如果Spring能处理这个问题肯定会更好…


阅读 503

收藏
2020-06-01

共1个答案

小编典典

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

为了使上述工作:-您必须以以下格式传递值
foo [MyTestA] = bar
foo [MyTestB] = bar2

现在,将诸如“ MyTestA”,“ MyTestB”等的字符串绑定到MyEnum,
您必须定义一个转换器。看看这个链接

2020-06-01