Spring 3.0 MVC绑定Enums区分大小写 [英] Spring 3.0 MVC binding Enums Case Sensitive

查看:203
本文介绍了Spring 3.0 MVC绑定Enums区分大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在Spring控制器中有一个RequestMapping,那么......

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

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

而产品是一个枚举。例如。 Product.Home

And Product is an enum. eg. Product.Home

当我请求页面时,mysite.com / home

When I request the page, 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?

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

我想保持url不区分大小写并且我的Java枚举用标准大写字母。

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

谢谢

解决方案

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>

添加到需要特殊转换的控制器

Add to controllers that need special conversion

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


推荐答案

从广义上讲,你想要创建一个新的PropertyEditor,为您执行规范化,然后在控制器中注册它,如下所示:

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());
 }

这篇关于Spring 3.0 MVC绑定Enums区分大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆