Multi-valued query parameters such as /test?x=value1&x=value2&x=value3 can be mapped to an array/list of String type (or of any other supported assignable type).
Multi-valued query parameters can also be mapped to MultiValueMap.
Examples
package com.logicbig.example;
import org.springframework.stereotype.Controller;
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.ResponseBody;
import java.util.List;
@Controller
public class ItemController {
@ResponseBody
@RequestMapping("/items")
public String handleRequest(@RequestParam("id") List<String> itemIds) {
String response = "";
for (String itemId : itemIds) {
response += "item with string id " + itemId + "<br/>";
}
return response;
}
@ResponseBody
@RequestMapping("/items2")
public String handleRequest2(@RequestParam("id") int[] itemIds) {
String response = "";
for (int itemId : itemIds) {
response += "item with int id " + itemId + "<br/>";
}
return response;
}
@ResponseBody
@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 Jetty (configured in pom.xml of example project below):
mvn jetty:run
Mapping to List
by making request
/items?id=1&id=2:
$ curl -s "http://localhost:8080/items?id=1&id=2" item with string id 1<br/>item with string id 2<br/>
Mapping to int[] by making request /items2?id=1&id=2:
$ curl -s "http://localhost:8080/items2?id=1&id=2" item with int id 1<br/>item with int id 2<br/>
Mapping to MultiValueMap by making request /items3?id=1&id=2:
$ curl -s "http://localhost:8080/items3?id=1&id=2" item from map with String id 1<br/>item from map with String id 2<br/>
Example ProjectDependencies and Technologies Used: - spring-webmvc 7.0.6 (Spring Web MVC)
Version Compatibility: 3.2.9.RELEASE - 7.0.6 Version compatibilities of spring-webmvc with this example: Versions in green have been tested.
- jakarta.servlet-api 6.1.0 (Jakarta Servlet API documentation)
- spring-test 7.0.6 (Spring TestContext Framework)
- junit-jupiter-engine 6.0.3 (Module "junit-jupiter-engine" of JUnit)
- JDK 25
- Maven 3.9.11
|