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());
}
RelaxedConversionService
andStringToEnumIgnoringCaseConverterFactory
in Spring Boot, but they are not public. – OrangeDogStringToEnumIgnoringCaseConverterFactory
stackoverflow.com/questions/55169848/… – Mohicane