简体   繁体   English

抽象类和Spring MVC @ ModelAttribute / @ RequestParam

[英]Abstract classes and Spring MVC @ModelAttribute/@RequestParam

I have a hierarchy of model classes in my Spring/Hibernate application. 我的Spring / Hibernate应用程序中具有模型类的层次结构。

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? 当向Spring MVC控制器提交POST表单时,是否有任何标准方法指定要提交的对象的类型,因此Spring可以实例化在接收方法的@ModelAttribute或@RequestParam中声明的类型的正确子类?

For example: 例如:

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
}

Jackson can deserialize JSON as a specific subtype using the @JsonTypeInfo annotation. Jackson可以使用@JsonTypeInfo批注将JSON反序列化为特定的子类型。 I'm hoping Spring can do the same. 我希望Spring可以做同样的事情。

Jackson can deserialize JSON as a specific subtype using the @JsonTypeInfo annotation. Jackson可以使用@JsonTypeInfo批注将JSON反序列化为特定的子类型。 I'm hoping Spring can do the same. 我希望Spring可以做同样的事情。

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. 假设您使用Jackson进行类型转换(如果Spring在类路径中找到它并且在XML中包含<mvc:annotation-driven/> ,则Spring将自动使用Jackson),那么它与Spring无关。 Annotate the types, and Jackson will instantiate the correct classes. 注释类型,Jackson将实例化正确的类。 Nevertheless, you will have to do instanceof checks in your Spring MVC controller method. 不过,您将必须在Spring MVC控制器方法中执行instanceof检查。

Update after comments: 评论后更新:

Have a look at 15.3.2.12 Customizing WebDataBinder initialization . 看一下15.3.2.12定制WebDataBinder初始化 You could use an @InitBinder method that registers an editor based on a request parameter: 您可以使用@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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM