如何在Spring-MVC方法中绑定抽象类的子类? [英] How to bind a subclass of an abstract class in a Spring-MVC method?

查看:377
本文介绍了如何在Spring-MVC方法中绑定抽象类的子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Spring-MVC控制器中给出保存"方法:

Given a "save" method in a Spring-MVC controller:

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

myModel参数中具有作为抽象类的属性:

with a property in the myModel parameter that is an abstract class:

public class MyModel {
    public AbstractFruit fruit;
}

有什么方法可以指定请求中特定子类(例如Apple)的使用?

Is there any way of specifying use of a particular subclass (e.g. Apple) in the request?

推荐答案

您可以在控制器类中使用自定义的初始化绑定器方法:

You can use custom init binder method in your controller class:

// 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表单绑定机制将正确设置Apple/Banana类中的所有字段.

Spring form binding mechanism will then correctly set all fields in Apple/Banana class.

这篇关于如何在Spring-MVC方法中绑定抽象类的子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆