简体   繁体   English

如何在Spring-MVC方法中绑定抽象类的子类?

[英]How to bind a subclass of an abstract class in a Spring-MVC method?

Given a "save" method in a Spring-MVC controller: 在Spring-MVC控制器中给定“保存”方法:

@RequestMapping(value = "/save")
public void save(@ModelAttribute(MY_KEY) final MyModel myModel) { ... }

with a property in the myModel parameter that is an abstract class: myModel参数中具有一个抽象类的属性:

public class MyModel {
    public AbstractFruit fruit;
}

Is there any way of specifying use of a particular subclass (eg Apple ) in the request? 有没有办法在请求中指定使用特定的子类(例如Apple )?

You can use custom init binder method in your controller class: 您可以在控制器类中使用自定义init绑定程序方法:

// Additionally using MY_KEY as "value" parameter of this annotation
// is not working in some cases
@InitBinder
public void initBinder(WebDataBinder webDataBinder, HttpServletRequest servletRequest) {

    // Probably you only want to init this when form is submitted
    if (!"POST".equalsIgnoreCase(httpServletRequest.getMethod()) {
        return;
    }

    // Filter out all request when we have nothing to do
    Object nonCastedTarget = webDataBinder.getTarget();
    if (nonCastedTarget == null || !(nonCastedTarget instanceof MyModel)) {
        return;
    }

    MyModel target = (MyModel) nonCastedTarget;
    if (/* some condition */) {
        target.setFruit(new Apple());
    } else {
        target.setFruit(new Banana());
    }
}

Spring form binding mechanism will then correctly set all fields in Apple/Banana class. 然后,Spring表单绑定机制将正确设置Apple / Banana类中的所有字段。

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

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