Spring's @RequestParam with Enum

You can create a custom converter that will return null instead of an exception when an invalid value is supplied.

Something like this:

@Configuration
public class MyConfig extends WebMvcConfigurationSupport {
   @Override
   public FormattingConversionService mvcConversionService() {
       FormattingConversionService f = super.mvcConversionService();
       f.addConverter(new MyCustomEnumConverter());
       return f;
   }
}

And a simple converter might look like this:

public class MyCustomEnumConverter implements Converter<String, SortEnum> {
    @Override
    public SortEnum convert(String source) {
       try {
          return SortEnum.valueOf(source);
       } catch(Exception e) {
          return null; // or SortEnum.asc
       }
    }
}

If you are using Spring Boot, this is the reason that you should not use WebMvcConfigurationSupport.

The best practice, you should implement interface org.springframework.core.convert.converter.Converter, and with annotation @Component. Then Spring Boot will auto load all Converter's bean. Spring Boot code

@Component
public class GenderEnumConverter implements Converter<String, GenderEnum> {
    @Override
    public GenderEnum convert(String value) {
        return GenderEnum.of(Integer.valueOf(value));
    }
}

Demo Project


you need to do the following

@InitBinder
public void initBinder(WebDataBinder dataBinder) {
    dataBinder.registerCustomEditor(YourEnum.class, new YourEnumConverter());
}

refer the following : https://machiel.me/post/java-enums-as-request-parameters-in-spring-4/