简体   繁体   English

Spring MVC中的多态形式绑定

[英]Polymorphic Form Binding in Spring MVC

Is it possible to give Spring MVC's form binding some kind of type hint to indicate what class to instantiate and populate with form data? 是否有可能为Spring MVC的表单绑定某种类型的提示,以指示实例化和填充表单数据的类?

I've got some quite unusual requirements to try and build a dynamic form, that represents a collection of different objects. 我有一些非常不寻常的要求尝试构建一个动态表单,它代表了不同对象的集合。 The user can add objects from a selection of types to this collection, and then set the properties for that object type using form elements. 用户可以将选定类型的对象添加到此集合,然后使用表单元素设置该对象类型的属性。 I can figure out how to create the form using jQuery, but I'm not sure how to get Spring to handle a load of POST data when it won't know what types to bind to in advance. 我可以弄清楚如何使用jQuery创建表单,但我不知道如何让Spring处理大量的POST数据,因为它不知道要提前绑定哪些类型。

One way that I can think of doing this is to write your own custom HandlerMethodArgumentResolver , which is responsible for translating the request into the argument values of the controller methods. 我可以想到这样做的一种方法是编写自己的自定义HandlerMethodArgumentResolver ,它负责将请求转换为控制器方法的参数值。 You should be able to create a custom annotation that will indicate to Spring MVC, that your custom handler method argument resolver will be resolving the specific annotated method arguments(say @CustomType Object argument ). 您应该能够创建一个自定义注释,指示Spring MVC,您的自定义处理程序方法参数解析器将解析特定的带注释的方法参数(比如@CustomType Object argument )。

Once the call comes into the handler resolver, you can probably determine the type that the json request should map to, and call the json mapper with the actual type. 一旦调用进入处理程序解析器,您可以确定json请求应映射到的类型,并使用实际类型调用json映射器。

You can register a custom argument resolver this way: 您可以这样注册自定义参数解析器:

<annotation-driven>
    <argument-resolvers>
        <beans:bean class="..CustomArgumentResolver"/>
    </argument-resolvers>
</annotation-driven>

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

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