2012-05-15 27 views
1

我正在將應用程序從Spring 2.0.7遷移到3.1.1,並且觸發了initBinder的問題。我們曾經有如下方法:@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}支持,除了命令/表單對象和 對應的驗證結果對象。

這樣做的正確方法是什麼?

回答

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

該代碼給出了相同的問題。該命令只是一個「對象」而不是我的註冊命令。 –

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())直接?

+0

該命令不應該是未初始化的,就是這樣。我認爲我的問題是我將舊的Spring類層次結構與註釋結合在一起。我現在介於兩者之間,試圖一次轉移到一個控制器的新方式。我有一箇舊的'formBackingObject',但由於這個不再被Spring調用,我用'@ ModelAttribute'做了一個新的方法,然後調用這個舊的'formBackingObject'。然而,'@ ModelAttribute'不會對我從方法返回的命令對象做任何事情,這是否正確?有沒有其他方法可以「登記」命令? –

+0

要初始化命令,請在方法上使用@ModelAttribute。我只是用例子編輯答案。 –

+0

我做到了。看來問題在於'initBinder'被多次調用。除了像上面那樣的'@ ModelAttribute'方法之外,我還有一個返回void的模型映射,並在其中設置了大量的東西。看起來initBinder被稱爲一切。我得到它在做一個instanceof檢查目標,但它似乎很難...? –

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(」東西「)而不是僅僅@InitBinder。這種方式@InitBinder不會被多次調用,而只會在遇到配置的對象時調用。

相關問題