从Spring MVC 3开始,不推荐使用AbstractCommandController
,因此您无法再在setCommandClass()
中指定命令类。而是在请求处理程序的参数列表中对命令类进行硬编码。例如,
@RequestMapping(method = RequestMethod.POST)
public void show(HttpServletRequest request, @ModelAttribute("employee") Employee employee)
我的问题是我正在开发一个允许用户编辑通用bean的通用页面,因此在运行时之前不知道命令类。如果变量beanClass
包含命令类,使用AbstractCommandController
,则只需执行以下操作,
setCommandClass(beanClass)
由于我不能将命令对象声明为方法参数,有没有办法让Spring绑定请求参数到请求处理程序主体中的泛型bean?
答案 0 :(得分:6)
命令对象的实例化是Spring需要知道命令类的唯一地方。但是,您可以使用@ModelAttribute
- 带注释的方法覆盖它:
@RequestMapping(method = RequestMethod.POST)
public void show(HttpServletRequest request,
@ModelAttribute("objectToShow") Object objectToShow)
{
...
}
@ModelAttribute("objectToShow")
public Object createCommandObject() {
return getCommandClass().newInstance();
}
顺便说一句,Spring也适用于真正的泛型:
public abstract class GenericController<T> {
@RequestMapping("/edit")
public ModelAndView edit(@ModelAttribute("t") T t) { ... }
}
@Controller @RequestMapping("/foo")
public class FooController extends GenericController<Foo> { ... }