Close

Spring MVC - Mapping Multi Valued Query Parameter with Arrays

[Last Updated: May 17, 2018]

Multi-valued query parameters such as /test?x=value1&x=value2&x=value3 can be mapped to an array of String type (or of any other supported assignable type).

Multi-valued query parameters can also be mapped to MultiValueMap.

Example

package com.logicbig.example;

import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController
public class ItemController {

  @RequestMapping("/items")
  public String handleRequest(@RequestParam("id") String[] itemIds) {
      String response = "";
      for (String itemId : itemIds) {
          response += "item with string id " + itemId + "<br/>";
      }
      return response;
  }

  @RequestMapping("/items2")
  public String handleRequest2(@RequestParam("id") int[] itemIds) {
      String response = "";
      for (int itemId : itemIds) {
          response += "item with int id " + itemId + "<br/>";
      }
      return response;
  }

  @RequestMapping("/items3")
  public String handleRequest3(@RequestParam MultiValueMap<String, String> queryMap) {
      String response = "";
      List<String> itemIds = queryMap.get("id");
      for (String itemId : itemIds) {
          response += "item from map with String id " + itemId + "<br/>";
      }
      return response;
  }
}

Output

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run

Mapping to String[] by making request /items?id=1&id=2:

Mapping to int[] by making request /items2?id=1&id=2:

Mapping to MultiValueMap by making request /items3?id=1&id=2:

Example Project

Dependencies and Technologies Used:

  • spring-webmvc 5.0.5.RELEASE: Spring Web MVC.
  • javax.servlet-api 3.0.1 Java Servlet API
  • JDK 1.8
  • Maven 3.3.9

Mapping Multi Valued Query Parameter with Array Select All Download
  • spring-multi-valued-query-parameter
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • ItemController.java

    See Also