如何使用Spring MVC使用@RequestParam捕获多个参数?

how to capture multiple parameters using @RequestParam using spring mvc?

假设单击了超链接,并使用以下参数列表myparam=myValue1&myparam=myValue2&myparam=myValue3触发了URL。 现在如何在Spring MVC中使用@RequestParam捕获所有参数?

我的要求是我必须捕获所有参数并将它们放在地图中。

请帮忙!


1
2
3
4
5
6
7
8
9
@RequestMapping(value ="users/newuser", method = RequestMethod.POST)  
public String saveUser(@RequestParam Map<String,String> requestParams) throws Exception{
   String userName=requestParams.get("email");
   String password=requestParams.get("password");

   //perform DB operations

   return"profile";
}

您可以按上述方式使用RequestParam。


看来你听不懂

1
Map<String,String>

因为您所有的参数都具有相同的名称" myparam"

尝试以下方法:

1
public ModelAndView method(@RequestParam("myparam") List<String> params) { }


要一次获取所有参数,请尝试以下操作:

1
public ModelAndView postResultPage(@RequestParam MultiValueMap<String, String> params)

@RequestParam java doc(3。段)中描述了此功能:

Annotation which indicates that a method parameter should be bound to a web request parameter. Supported for annotated handler methods in Servlet and Portlet environments.

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.

If the method parameter is Map or MultiValueMap and a parameter name is not specified, then the map parameter is populated with all request parameter names and values.


从Spring 3.0开始,您还可以使用MultiValueMap实现此目的:

一个简单的例子是:

1
2
3
4
5
6
7
8
9
10
11
12
public String someMethod(@RequestParam MultiValueMap<String,String> params) {

    final Iterator<Entry<String, List<String>>> it = params.entrySet().iterator();

    while(it.hasNext()) {
        final String k = it.next().getKey();
        final List<String> values = it.next().getValue();
    }

    return"dummy_response";

}


如果有人尝试在Spring Boot中执行相同的操作,请使用RequestBody代替RequestParam


Spring mvc可以支持ListSetMap参数,但不包含@RequestParam。

如果您的对象是User.java,则以List为例,它像这样:

1
2
3
4
5
6
public class User {
    private String name;
    private int age;

    // getter and setter
}

而且您想要传递List的参数,则可以使用如下网址

1
http://127.0.0.1:8080/list?users[0].name=Alice&users[0].age=26&users[1].name=Bob&users[1].age=16

记住要对URL进行编码,编码后的URL是这样的:

1
http://127.0.0.1:8080/list?users%5B0%5D.name=Alice&users%5B0%5D.age=26&users%5B1%5D.name=Bob&users%5B1%5D.age=16

ListSetMap的示例显示在我的github中。