Close

Spring MVC - Mapping Query Parameters To Enum

[Updated: May 17, 2018, Created: May 17, 2018]

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 constants as query param keys, then we can use MultiValueMap, but Spring does not convert String parameter key to enum in that case. We have to manually convert String key to the target enum constant.

Example

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:

Making request fruits?name=Apple&name=Banana:

Using enum as query key with fruitsCount?Apple=3&Banana=5:

Example Project

Dependencies and Technologies Used:

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

Mapping Query Parameters To Enum Select All Download
  • spring-query-parameter-mapping-enum
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • FruitController.java

    See Also