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 String
s (or other objects?
Thanks.
Alex
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.
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.
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.
"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){ .... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With