簡體   English   中英

如何在Spring-MVC方法中綁定抽象類的子類?

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

在Spring-MVC控制器中給定“保存”方法:

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

myModel參數中具有一個抽象類的屬性:

public class MyModel {
    public AbstractFruit fruit;
}

有沒有辦法在請求中指定使用特定的子類(例如Apple )?

您可以在控制器類中使用自定義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表單綁定機制將正確設置Apple / Banana類中的所有字段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM