Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Spring MVC handle multivalue query parameter?

Tags:

spring-mvc

Having this http://myserver/find-by-phones?phone=123&phone=345 request, is it possible to handle with something like this:

@Controller public class Controller{     @RequestMapping("/find-by-phones")     public String find(List<String> phones){        ...     } } 

Can Spring MVC some how convert multi-value param phones to a list of Strings (or other objects?

Thanks.

Alex

like image 986
AlexV Avatar asked Mar 19 '12 10:03

AlexV


People also ask

How do you pass multiple query parameters in a REST URL spring boot?

Query parameters are passed after the URL string by appending a question mark followed by the parameter name , then equal to (“=”) sign and then the parameter value. Multiple parameters are separated by “&” symbol.

How do I pass multiple parameters in RequestParam?

Similarly, if the request has more than one query string parameter, we can use @RequestParam annotation individually on the respective method arguments. Our controller reads id and name parameters from the request. Executing the respective GET request, we see that both request parameters are mapped correctly.

What is query parameter in spring?

Spring @RequestParam @RequestParam is a Spring annotation used to bind a web request parameter to a method parameter. It has the following optional elements: defaultValue - used as a fallback when the request parameter is not provided or has an empty value. name - name of the request parameter to bind to.


1 Answers

"Arrays" in @RequestParam are used for binding several parameters of the same name:

phone=val1&phone=val2&phone=val3 

-

public String method(@RequestParam(value="phone") String[] phoneArray){     .... } 

You can then convert it into a list using Arrays.asList(..) method

EDIT1:

As suggested by emdadul, latest version of spring can do like below as well:

public String method(@RequestParam(value="phone", required=false) List<String> phones){     .... } 
like image 193
fmucar Avatar answered Nov 22 '22 13:11

fmucar