我的应用程序模型中有一个父类及其子类。
并具有以下 Controller 方法:
@RequestMapping(method=RequestMethod.POST, value="/page")
public String postMethod(Model model, Parent obj, BindingResult result) {
// do something
}
但我希望它能够处理通过表单发布的子类的实例。
我怎样才能做到这一点?
最佳答案
您可以创建所需类型的对象作为隐式模型属性:
@ModelAttribute("parent")
public Parent createChild(@RequestParam("type") String type) {
if ("foo".equals(type)) return new Foo();
else if ("bar".equals(type)) return new Bar();
else return null;
}
由于 Spring 不会自动记住传递给表单的对象类型,因此您需要自己添加一个隐藏表单字段,其值指定对象的类型(type
字段)在上面的例子中)。
另一个选择是通过将对象存储在 session 中来避免从头开始创建对象。可以使用 @SessionAttributes
注解进行配置,请参阅 15.3.2.9 Specifying attributes to store in a session with @SessionAttributes .
关于java - 如何在 spring-mvc 中将子类传递给 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7413996/