Spring 3.0 MVC binding Enums Case Sensitive

spring boot jackson enum case insensitive
java enum case insensitive
spring boot requestparam case insensitive
spring requestbody enum
enum with value spring
enum spring property
enum in spring boot
spring boot enum converter

If I have a RequestMapping in a Spring controller like so...

@RequestMapping(method = RequestMethod.GET, value = "{product}")
public ModelAndView getPage(@PathVariable Product product)

And Product is an enum. eg. Product.Home

When I request the page, mysite.com/home

I get

Unable to convert value "home" from type 'java.lang.String' to type 'domain.model.product.Product'; nested exception is java.lang.IllegalArgumentException: No enum const class domain.model.product.Product.home

Is there a way to have the enum type converter to understand that lower case home is actually Home?

I'd like to keep the url case insensitive and my Java enums with standard capital letters.

Thanks

Solution

public class ProductEnumConverter extends PropertyEditorSupport
{
    @Override public void setAsText(final String text) throws IllegalArgumentException
    {
        setValue(Product.valueOf(WordUtils.capitalizeFully(text.trim())));
    }
}

registering it

<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
        <property name="customEditors">
            <map>
                <entry key="domain.model.product.Product" value="domain.infrastructure.ProductEnumConverter"/>
            </map>
        </property>
    </bean>

Add to controllers that need special conversion

@InitBinder
public void initBinder(WebDataBinder binder)
{
    binder.registerCustomEditor(Product.class, new ProductEnumConverter());
} 

Broadly speaking, you want to create a new PropertyEditor that does the normalisation for you, and then you register that in your Controller like so:

@InitBinder
 public void initBinder(WebDataBinder binder) {

  binder.registerCustomEditor(Product.class,
    new CaseInsensitivePropertyEditor());
 }

java - Spring 3.0 MVC binding Enums Case Sensitive, Is there a way to have the enum type converter to understand that lower case home is actually Home? I'd like to keep the url case insensitive and my Java  Spring 3.0 MVC binding Enums Case Sensitive @RequestMapping(method = RequestMethod.GET, value = "{product}") public ModelAndView getPage(@PathVariable Product product)


I think you will have to implement a Custom PropertyEditor.

Something like this:

public class ProductEditor extends PropertyEditorSupport{

    @Override
    public void setAsText(final String text){
        setValue(Product.valueOf(text.toUpperCase()));
    }

}

See GaryF's answer on how to bind it

Here's a more tolerant version in case you use lower case in your enum constants (which you probably shouldn't, but still):

@Override
public void setAsText(final String text){
    Product product = null;
    for(final Product candidate : Product.values()){
        if(candidate.name().equalsIgnoreCase(text)){
            product = candidate;
            break;
        }
    }
    setValue(product);
}

Spring 3.0 MVC binding Enums Case Sensitive, Spring 3.0 MVC binding Enums Case Sensitive. Question. If I have a RequestMapping in a Spring controller like so @RequestMapping(method  Spring MVC entry point. Ask Question Asked 7 years, 4 months ago. Active 6 years, 11 months ago. Viewed 6k times Spring 3.0 MVC binding Enums Case Sensitive. 16.


It's also possible to create a generic converter that will work with all Enums like this:

public class CaseInsensitiveConverter<T extends Enum<T>> extends PropertyEditorSupport {

    private final Class<T> typeParameterClass;

    public CaseInsensitiveConverter(Class<T> typeParameterClass) {
        super();
        this.typeParameterClass = typeParameterClass;
    }

    @Override
    public void setAsText(final String text) throws IllegalArgumentException {
        String upper = text.toUpperCase(); // or something more robust
        T value = T.valueOf(typeParameterClass, upper);
        setValue(value);
    }
}

Usage:

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(MyEnum.class, new CaseInsensitiveConverter<>(MyEnum.class));
}

Or globally as skaffman explains

java - Spring 3.0 MVC binding Enums Case Sensitive -, Is there a way to have the enum type converter to understand that lower case home is actually Home? I'd like to keep the url case insensitive and my Java enums  Spring 3.0 MVC binding Enums Case Sensitive. Если у меня есть RequestMapping в controllerе Spring, например … @RequestMapping(method = RequestMethod.GET, value = “{product}”) public ModelAndView getPage(@PathVariable Product product) И Продукт – это перечисление. например.


In Spring Boot 2 you can use ApplicationConversionService. It provides some useful converters, especially org.springframework.boot.convert.StringToEnumIgnoringCaseConverterFactory - responsible for converting a string value to an enum instance. This is the most generic (we don't need to create separate converter/formatter per enum) and simplest solution I've managed to find.

import org.springframework.boot.convert.ApplicationConversionService;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class AppWebMvcConfigurer implements WebMvcConfigurer {
    @Override
    public void addFormatters(FormatterRegistry registry) {
        ApplicationConversionService.configure(registry);
    }
}

I know that questions is regarding Spring 3 but this is the first result in google when searching for a spring mvc enums case insensitive phrase.

Spring requestparam enum case insensitive, is there way have enum type converter understand lower case home home? i'd keep url case insensitive , java enums standard capital letters. thanks. solution 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


To add to @GaryF's answer, and to address your comment to it, you can declare global custom property editors by injecting them into a custom AnnotationMethodHandlerAdapter. Spring MVC normally registers one of these by default, but you can give it a specially-configured one if you choose, e.g.

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  <property name="webBindingInitializer">
    <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
      <property name="propertyEditorRegistrars">
        <list>
          <bean class="com.xyz.MyPropertyEditorRegistrar"/>
        </list>
      </property>
    </bean>
  </property>
</bean>

MyPropertyEditorRegistrar is an instance of PropertyEditorRegistrar, which in turns registers custom PropertyEditor objects with Spring.

Simply declaring this should be enough.

Using Enums as Request Parameters in Spring, OAS 3 This page applies to OpenAPI 3 – the latest version of the OpenAPI I have case insensitive URLS in Spring MVC with annotated mappings works perfectly. Double' Spring Boot bind @Value to Enum case insensitive Specifying with  Java enums as Request Parameters in Spring 4 April 7, 2014 Looking for a solution to pass enum values as Request Parameters in URIs using Spring is quite easy. However, my enum values are always fully uppercase. I do not like having capitalized characters in my URIs, so I went looking for a solution.


A Custom Data Binder in Spring MVC, mode=unknown, Spring will fail to convert it to the specified enum type. In this case, we'll get a ConversionFailedException. 3. Custom Converter. Spring JS Ajax call - enum data binding failing to convert but strings working. Ask Question Spring 3.0 MVC binding Enums Case Sensitive. 1. data-binding Spring.


Java enums as Request Parameters in Spring 4 · Machiel, Now we can use our Enum as a RequestParameter: ? 1. 2. 3. 4. @GetMapping. Spring 3.0 MVC binding Enums Case Sensitive. 13. Jackson + Tomcat - java.lang.VerifyError: Cannot inherit from final class. 205. Spring RestTemplate - how to enable


Looking for a solution to pass enum values as Request Parameters in com/​questions/4617099/spring-3-0-mvc-binding-enums-case-sensitive. Name matching is not case-sensitive. Converts the string "true" into boolean true . The framework then calls the GetById method, passing in 2 for the id parameter, and true for the dogsOnly parameter.