抽象类和Spring MVC @ ModelAttribute / @ RequestParam [英] Abstract classes and Spring MVC @ModelAttribute/@RequestParam
问题描述
我的Spring / Hibernate应用程序中有一个模型类层次结构。
I have a hierarchy of model classes in my Spring/Hibernate application.
将一个POST表单提交给Spring MVC控制器时,是否有任何标准的指定方式提交的对象的类型,因此Spring可以实例化接收方法的@ModelAttribute或@RequestParam中声明的类型的正确子类?
When submitting a POST form to a Spring MVC controller, is there any standard way of specifying the type of the object being submitted, so Spring can instantiate the correct subclass of the type declared in the receiving method's @ModelAttribute or @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
}
杰克逊可以使用@JsonTypeInfo注释将JSON反序列化为特定子类型。我希望Spring可以这样做。
Jackson can deserialize JSON as a specific subtype using the @JsonTypeInfo annotation. I'm hoping Spring can do the same.
推荐答案
杰克逊可以将JSON反序列化为特定的子类型使用
@JsonTypeInfo注释。我希望Spring能做同样的事情。
Jackson can deserialize JSON as a specific subtype using the @JsonTypeInfo annotation. I'm hoping Spring can do the same.
假设你使用Jackson进行类型转换(如果发现它,Spring会自动使用Jackson类路径,你的XML中有< mvc:annotation-driven />
,那么它与Spring无关。注释类型,Jackson将实例化正确的类。不过,您必须在Spring MVC控制器方法中执行 instanceof
检查。
Assuming you use Jackson for type conversion (Spring uses Jackson automatically if it finds it on the classpath and you have <mvc:annotation-driven/>
in your XML), then it has nothing to do with Spring. Annotate the types, and Jackson will instantiate the correct classes. Nevertheless, you will have to do instanceof
checks in your Spring MVC controller method.
评论后更新:
看看 15.3.2.12自定义WebDataBinder初始化。您可以使用 @InitBinder
方法根据请求参数注册编辑器:
Have a look at 15.3.2.12 Customizing WebDataBinder initialization. You could use an @InitBinder
method that registers an editor based on a request parameter:
@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);
}
这篇关于抽象类和Spring MVC @ ModelAttribute / @ RequestParam的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!