[英]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.