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