java - Spring 3.0 MVC 绑定(bind)枚举大小写敏感

标签 java spring spring-mvc

如果我在 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/

相关文章:

javascript - 在 Spring MVC 中使用没有表单的多部分

java - MongoDB - Spring - 保存对象导致 StackOverflowError

java - 如何使用Java中的RenderSnake库生成HTML表格?

Java读取西里尔语CSV文件,写入奇怪的字符

当值相等时,Spring security 编码的密码看起来不像 BCrypt

java - 库中存储库的 NoSuchBeanDefinitionException

java - 如何在 Spring Boot Web 应用程序中配置 2 个单独的过滤器?

java - 带有 BindingResult 的 @Valid JSON 请求导致 IllegalStateException

java - 将不同类中的 BigInteger 写入文件

java - 如何保存变量的值并防止它们在递归时改变?还有递归协助?