2011-09-07 93 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

相关问题