Following example shows how to use Java Enums with @RequestParam to map query values to parameters of Enum type.
If we want to use enum constant as query param keys, then we can use MultiValueMap, but we have to manually convert that to the target enum constant.
Example The example demonstrates three things:
- Mapping a single query param string to an
Enum via @RequestParam — Spring handles this automatically using Enum.valueOf().
- Mapping an array of enum values from repeated query params.
- Manually parsing
MultiValueMap<String, Integer> when the enum is used as the key (not the value), since Spring doesn't auto-convert map keys.
The Controller
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.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@RestController
public class FruitController {
public enum Fruit {
Apple,
Banana,
Orange
}
@RequestMapping("/fruit")
public String handleRequest(@RequestParam("name") Fruit fruit) {
return "response for " + fruit;
}
@RequestMapping("/fruits")
public String handleRequest2(@RequestParam("name") Fruit[] fruits) {
return "response for " + Arrays.toString(fruits);
}
@RequestMapping("/fruitsCount")
public String handleRequest3(@RequestParam MultiValueMap<String, Integer> queryMap) {
String response = "";
for (Map.Entry<String, List<Integer>> entry : queryMap.entrySet()) {
Fruit f = null;
try {
f = Fruit.valueOf(entry.getKey());
} catch (IllegalArgumentException e) {
return "Not a valid fruit: " + entry.getKey();
}
List<Integer> value = entry.getValue();
if (value.size() > 0) {
response += f + "=" + value.get(0) + "<br/>";
}
}
return response;
}
}
Output
Making request /fruit?name=Orange:
$ curl -s "http://localhost:8080/fruit?name=Orange" response for Orange
Making request fruits?name=Apple&name=Banana:
$ curl -s "http://localhost:8080/fruits?name=Apple&name=Banana" response for [Apple, Banana]
Using enum as query key with fruitsCount?Apple=3&Banana=5:
$ curl -s "http://localhost:8080/fruitsCount?Apple=3&Banana=5" Apple=3<br/>Banana=5<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
|