Can Spring MVC handle multivalue query parameter?

后端 未结 3 681
终归单人心
终归单人心 2020-11-30 08:14

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

@Controller
publi         


        
相关标签:
3条回答
  • 2020-11-30 08:50

    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
    
    0 讨论(0)
  • 2020-11-30 08:53

    "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){
        ....
    }
    
    0 讨论(0)
  • 2020-11-30 08:55

    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.

    0 讨论(0)
提交回复
热议问题