【问题标题】:spring mvc4 initBinder modelspring mvc4 initBinder 模型
【发布时间】:2025-12-24 02:30:12
【问题描述】:

我需要在自定义编辑器中访问一些模型信息。我尝试将 ModelMap 用作 initBinder 参数,但在运行时出现拒绝错误。 有什么想法吗?

public void initBinder(WebDataBinder binder, WebRequest request) {
    binder.registerCustomEditor(MyData.class, new MyCustomEditor(model));
}

TIA 冰72

【问题讨论】:

    标签: spring model-view-controller model controller


    【解决方案1】:

    @InitBinder 只是注册Editors 和Validators,映射HTML

    的ModelMap 将在initBinder 之后,@RequestMapping 方法之前创建。

    您可以在您的 CustomEditor 中使用该服务,并格式化您将创建的 ModelMap 的字段。

    public class MyCustomEditor extends PropertyEditorSupport {
    
        private YourService service;
    
        public MyCustomEditor(YourService service){
            this.service = service;
        }
    
        @Override
        public void setAsText(String text){
            // TODO service can work here
            setValue(text);
        }
    
        @Override
        public String getAsText(){
            // TODO service can work here
            return (String) getValue();
        }
    
    }
    

    @Resource
    YourService yourService;
    
    @InitBinder
    protected void initBinder(WebDataBinder binder){
        binder.registerCustomEditor(MyData.class, "fieldInMyData", new MyCustomEditor(yourService));
    }
    

    【讨论】: