Abstract classes and Spring MVC @ModelAttribute/@RequestParam

前端 未结 1 1911
谎友^
谎友^ 2021-01-04 18:40

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 specifyi

1条回答
  •  既然无缘
    2021-01-04 19:18

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

    0 讨论(0)
提交回复
热议问题