java - 未调用 initBinder 方法来从 String 转换为 Enum

标签 java spring-3 property-editor spring-mvc-initbinders

我正在测试 @InitBinder 注释,以便我可以在 Web 请求期间将 String 对象转换为适当的 Enum 对象。

我创建了以下简单的Enum:

SampleEnum.java

public enum SampleEnum {
    ONE,
    TWO,
    THREE,
    FOUR,
    FIVE;
}

然后,我创建了一个编辑器,扩展了从 @InitBinder 代码调用的 PropertyEditorSupport:

EnumPropertyEditor.java

@SuppressWarnings("rawtypes")
public class EnumPropertyEditor extends PropertyEditorSupport {
    private Class clazz;

    public EnumPropertyEditor(Class clazz) {
        this.clazz = clazz;
    }

    @Override
    public String getAsText() {
        return (getValue() == null ? "" : ((Enum) getValue()).name());
    }

    @SuppressWarnings("unchecked")
    @Override
    public void setAsText(String text) {
        Enum e = Enum.valueOf(clazz, text);
        setValue(e);
    }
}

然后,在我的 Controller 中,我添加了 @InitBinder 和一个简单的请求映射:

Controller

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

@RequestMapping(method = POST, value = "/postSampleEnum")
@ResponseBody
public SampleEnum postSampleEnum(@RequestBody SampleEnum sampleEnum) {
    return sampleEnum;  
}

根据我的理解,对此 Controller 方法的请求应尝试将字符串值转换为 SampleEnum 对象。但是,initBinder、请求映射方法或 EnumPropertyEditor 中的任何方法均未命中断点。

我正在 FireFox 中使用 RESTClient 进行测试,并尝试发送请求正文“THREE”,我希望它能够工作。相反,无论请求正文中有什么内容,我都会收到 415 错误。 (服务器拒绝了该请求,因为请求实体的格式不为所请求的方法()所请求的资源所支持。)

如果我将请求映射更改为接受字符串而不是 SampleEnum,则将调用 postSampleEnum 并且不使用自定义编辑器(如预期)。

我是否缺少任何允许调用自定义编辑器代码的内容?继续调试此问题的最佳方法是什么?

最佳答案

首先,我忘记将 application/json 内容类型添加到 RESTClient 中的请求 header 中。 >_<

whoops

但是,我注意到代码执行仍然没有通过自定义属性编辑器。正如 GriffeyDog 所说,看起来代码只有在我切换到 RequestParamModelAttribute 时才会执行。

关于java - 未调用 initBinder 方法来从 String 转换为 Enum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16800744/

相关文章:

java - MVC Java Config - HandlerInterceptor 不排除路径

c# usercontrol 设置自定义属性的选项列表

java - 使用递归时重置结果集

java - Spring 启动+ webflux : context lost when running some steps in parallel

java - 我的菜单中未应用动态 css(tiles + spring 3.0)

spring - 如何在 Spring 3 中的 Controller 内生成 URI

delphi - 如何在设计时调用组件的属性编辑器

java - 将属性编辑器应用于模型中的对象

c# - 数组内存分配——分页

java - 如何在 Selenium 中将 LI 与 UL 分开