2011-09-07 97 views
8

我在Spring/Hibernate應用程序中有一個模型類層次結構。抽象類和Spring MVC @ ModelAttribute/@ RequestParam

當向Spring MVC控制器提交POST表單時,是否有任何指定被提交對象類型的標準方式,所以Spring可以實例化在接收方法的@ModelAttribute或@RequestParam中聲明的類型的正確子類?

例如:

public abstract class Product {...} 
public class Album extends Product {...} 
public class Single extends Product {...} 


//Meanwhile, in the controller... 
@RequestMapping("/submit.html") 
public ModelAndView addProduct(@ModelAttribute("product") @Valid Product product, BindingResult bindingResult, Model model) 
{ 
...//Do stuff, and get either an Album or Single 
} 

傑克遜可以反序列化JSON作爲使用@JsonTypeInfo註釋的亞型特異性。我希望Spring能做同樣的事情。

回答

6

Jackson可以使用@JsonTypeInfo批註將JSON反序列化爲特定的子類型。我希望Spring能做同樣的事情。

假設你使用傑克遜進行類型轉換(Spring使用自動傑克遜,如果它發現它的類路徑中,你必須在你的XML <mvc:annotation-driven/>),那麼它無關春天。註釋類型,Jackson將實例化正確的類。不過,你必須在你的Spring MVC控制器方法中進行instanceof檢查。評論後

更新:

看一看15.3.2.12 Customizing WebDataBinder initialization。你可以使用一個@InitBinder方法註冊基於請求參數編輯:

@InitBinder 
public void initBinder(WebDataBinder binder, HttpServletRequest request) { 
    String productType = request.getParam("type"); 

    PropertyEditor productEditor; 
    if("album".equalsIgnoreCase(productType)) { 
     productEditor = new AlbumEditor(); 
    } else if("album".equalsIgnoreCase(productType)) 
     productEditor = new SingleEditor(); 
    } else { 
     throw SomeNastyException(); 
    } 
    binder.registerCustomEditor(Product.class, productEditor); 
} 
+0

謝謝你,我的意思是這是可能的,當_not_提交JSON有效載荷,而普通帖子的形式提交。 –

+0

@Deejay確定更新了我的答案 –

+0

嗨,我嘗試解決類似的問題,但沒有結果..這我我的問題:http://stackoverflow.com/questions/21550238/how-instantiate-a-concrete-class- in-init-binder可以幫助我嗎? – Teo

相關問題