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.
It’s actually quite simple, first off you simply configure your route to accept the parameters. Here you’ll see how that is done, this is my ExchangeController
:
@RequestMapping(value = "/exchange/{currencyOne}/{currencyTwo}", method = RequestMethod.GET)
public String index(
@PathVariable Currency currencyOne,
@PathVariable Currency currencyTwo,
ModelMap map) {
map.addAttribute("currencyOne", currencyOne);
map.addAttribute("currencyTwo", currencyTwo);
return "exchange/index";
}
This is done in your controller obviously. Now if you would navigate to /exchange/ENUM_VAL_1/ENUM_VAL_2 (depending on your enum values, of course) you would simply get your page. However you will get a 404 Not Found
when you try to use the lowercase values.
To solve this problem you’ll first have to create a parameter converter. In my case it looks like this:
public class CurrencyEnumConverter extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
String capitalized = text.toUpperCase();
Currency currency = Currency.valueOf(capitalized);
setValue(currency);
}
}
Clear, right? Now you’ll have to register it:
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="com.mtech.easyexchange.model.Currency"
value="com.mtech.easyexchange.web.converter.CurrencyEnumConverter" />
</map>
</property>
</bean>
Where the key is your enum and the value is the class that converts the string to the correct parameter.
Now you’ll have to add the parameter converter to your controller. Simply add the following to your controller, in my case the ExchangeController
.
@InitBinder
public void initBinder(WebDataBinder dataBinder) {
dataBinder.registerCustomEditor(Currency.class, new CurrencyEnumConverter());
}
Now Spring is aware that it will have to apply the Converter on your enumeration.
Source: https://stackoverflow.com/questions/4617099/spring-3-0-mvc-binding-enums-case-sensitive
Let me know if it works for you, or if you have any improvements or suggestions!