java / beginner
Snippet
Handling Query Parameter Arrays in Spring Controllers
Spring automatically converts comma-separated URL query parameters into standard Java primitive arrays like int[]. This snippet demonstrates receiving an array parameter and accessing its length and index elements for batch request processing.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
@RestController@RequestMapping("/api/items")public class ItemController {@GetMapping("/batch")public String getItemsByIds(@RequestParam("ids") int[] itemIds) {int totalCount = itemIds.length;int firstId = totalCount > 0 ? itemIds[0] : -1;return "Requested " + totalCount + " items. First ID: " + firstId;}}
spring
Breakdown
1
public String getItemsByIds(@RequestParam("ids") int[] itemIds) {
Binds comma-delimited values from the 'ids' query parameter into a native integer array.
2
int totalCount = itemIds.length;
Inspects the length property of the array to count how many IDs were passed.