如果我在 Spring Controller 中有这样的 RequestMapping...
@RequestMapping(method = RequestMethod.GET, value = "{product}")
public ModelAndView getPage(@PathVariable Product product)
Product 是一个枚举。例如。产品.首页
当我请求页面时,mysite.com/home
我明白了
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
有没有办法让枚举类型转换器理解小写的 home 实际上是 Home?
我想保持 url 不区分大小写,并且我的 Java 枚举使用标准大写字母。
谢谢
解决方案
public class ProductEnumConverter extends PropertyEditorSupport
{
@Override public void setAsText(final String text) throws IllegalArgumentException
{
setValue(Product.valueOf(WordUtils.capitalizeFully(text.trim())));
}
}
注册
<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>
添加到需要特殊转换的 Controller
@InitBinder
public void initBinder(WebDataBinder binder)
{
binder.registerCustomEditor(Product.class, new ProductEnumConverter());
}
最佳答案
一般来说,您想创建一个新的 PropertyEditor 来为您进行规范化,然后像这样在 Controller 中注册它:
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Product.class,
new CaseInsensitivePropertyEditor());
}
关于java - Spring 3.0 MVC 绑定(bind)枚举大小写敏感,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4617099/