给定 Spring-MVC 控制器中的“保存”方法:
@RequestMapping(value = "/save")
public void save(@ModelAttribute(MY_KEY) final MyModel myModel) { ... }
拥有位于myModel
参数是一个抽象类:
public class MyModel {
public AbstractFruit fruit;
}
有没有什么方法可以指定特定子类的使用(例如Apple
)在请求中?
您可以在控制器类中使用自定义 init binder 方法:
// 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 类中的所有字段。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)