54

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

2
  • 2
    find(@RequestParam(required=false, value="phone") List<String> phones) should work. This works for url?phone=123&phone=345 and also for url?phone=123,345 and for null parameter value like url or url?phone= I hope this helps anyone looking for this solution :) Commented Mar 16, 2016 at 14:45
  • 1
    If you have multiple parameters all of which can have multiple values, use a MultiValueMap. See stackoverflow.com/questions/22398892/… Commented Jan 16, 2018 at 19:58

3 Answers 3

92

"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){
    ....
}
Sign up to request clarification or add additional context in comments.

9 Comments

if there is not a single param out there, will phoneArray be null or be an empty array ?
Spring can put the values directly into a list: @RequestParam(value="phone") List<String> phones. Not sure if/when this was changed, but it works in Spring 3.0.5.
@Nailgun can you set some sort of proper default parameter and generate an empty Array or do just have to handle the null? Thank you
what about form element name will it be phone[ ] or phone or phone[0],phone[1] ..... ? I have 25 mcq questions with 4 radio button for each question.
Element name is going to be phone
|
11

Spring can convert the query param directly into a List or even a Set

for example:

 @RequestParam(value = "phone", required = false) List<String> phones

or

 @RequestParam(value = "phone", required = false) Set<String> phones

Comments

4

I had an issue with indexed querystring like

http://myserver/find-by-phones?phone[0]=123&phone[1]=345
and only handling with
MultiValueMap<String, String>
worked for me. Neither List or String[] were handling it properly.

I also tried

@RequestParam("phones[]")
but RequestParamMethodArgumentResolver is looking explicitly for phones[] ignoring indexes. So that is why I decided to let RequestParamMapMethodArgumentResolver handle it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.