Abstract classes and Spring MVC @ModelAttribute/@RequestParam

穿精又带淫゛_ 提交于 2019-12-18 20:01:35

问题


I have a hierarchy of model classes in my Spring/Hibernate application.

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?

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. I'm hoping Spring can do the same.


回答1:


Jackson can deserialize JSON as a specific subtype using the @JsonTypeInfo annotation. I'm hoping Spring can do the same.

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.

Update after comments:

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);
}


来源:https://stackoverflow.com/questions/7336920/abstract-classes-and-spring-mvc-modelattribute-requestparam

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!