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

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

问题描述

如果我在 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 是一个枚举.例如.产品.首页

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

有没有办法让 enum 类型转换器理解小写的 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 来为您进行规范化,然后像这样在您的 Controller 中注册它:

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 绑定枚举区分大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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