1

我正在将应用程序从 Spring 2.0.7 迁移到 3.1.1,但遇到了 initBinder 问题。我们曾经有看起来像的方法

protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
    MyCommand command = (MyCommand)binder.getTarget();
    binder.registerCustomEditor(CustomerCard.class, createEditorFromCommand(command));
}

目标由 PropertyEditor 使用。当我将其设置为带注释的控制器时,不再调用此方法,因此我添加了@InitBinder注释:

@InitBinder
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
    MyCommand command = (MyCommand)binder.getTarget();
    binder.registerCustomEditor(CustomerCard.class, createEditorFromCommand(command));
}

不幸的binder.getTarget()是,这只是一些默认对象。@InitBinder 的文档还指出,我也无法将命令作为参数获取:

此类 init-binder 方法支持 {@link RequestMapping} 支持的所有参数,除了命令/表单对象和相应的验证结果对象。

这样做的正确方法是什么?

4

3 回答 3

0
@RequestMapping
// binder will return MyCommand on getTarget()
public void handleMyCommand(MyCommand c) {  
 ...
}

// initialize command before handleMyCommand method call
@ModelAttribute
public MyCommand initializeMyCommand() {
   // perform initialization.
}

@InitBinder
protected void initBinder(WebDataBinder binder) {
   MyCommand c  = (MyCommand) binder.getTarget();
   binder.registerCustomEditor(CustomerCard.class, createEditorFromCommand(c));
}

但是,由于命令被统一化了¿你为什么不createEditorFromCommand(new MyCommand())直接调用?

于 2012-05-15T23:19:27.607 回答
0
@InitBinder
protected void initBinder(WebDataBinder binder) {
  MyCommand command = (MyCommand)binder.getTarget();
  binder.registerCustomEditor(CustomerCard.class, createEditorFromCommand(command));
}
于 2012-05-15T16:29:32.363 回答
0

派对可能有点晚了,但仍然 - 这是一种在 @InitBinder 方法中引用模型(命令)对象的方法:

@InitBinder("commandName")
public void initBinder(WebDataBinder binder) throws Exception {
   CommandClass command = (CommandClass) binder.getTarget();
   binder.registerCustomEditor(Some.class, new SomeEditor(command.getOptions());
}

@ModelAttribute("commandName")
public OrderItem createCommand(HttpServletRequest request) {
   return new CommandClass();
}

放置@InitBinder("something") 而不仅仅是@InitBinder 可能是个好主意。这样@InitBinder 不会被多次调用,而只会在遇到配置的对象时调用。

于 2014-05-21T23:17:40.900 回答