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

Solution 1:

@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";
}

You could use RequestParam in the above mentioned manner.

Solution 2:

It seems you can't get

Map<String,String>

because all your params have same name "myparam"

Try this instead:

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

Solution 3:

To get all parameters at once try this:

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

This feature is described in the @RequestParam java doc (3. Paragraph):

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<String, String> or MultiValueMap<String, String> and a parameter name is not specified, then the map parameter is populated with all request parameter names and values.

Solution 4:

As of Spring 3.0, you can also use MultiValueMap to achieve this:

A rudimentary example would be:

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";

}

Solution 5:

If anyone is trying to do the same in Spring Boot, use RequestBody in place of RequestParam